TechiesWeb

Tips & Tricks on ASP.NET MVC, Ajax, jQuery, Entity Framework

Starting Entity Framework Codefirst Approach Part- 2

This is the second part of my Entity Framework Code First Tutorial for beginners. If you want to start fresh , Visit the first part here.

If you tried the first part, while creating the database using code first approach, you might have noticed that our columns of string type is created as nullable columns of type nvarachar and is having the MAX size.

 

Obviously it is not a good idea to create table columns like this. We need to be more specific about what we are going to built and work with. So if you want to specify the size  /nullabilty, we can do that as well in few different ways

1) Data Annotation

Data Annotations are attributes we can apply to the class members. By decorating a class memmber / Property with data annotation, we can achieve the
following things

1) Impose some validations on the entity
2) Specify how the data is gonna look like in the UI when displayed
3) Specify some relationships between entities

 

 

Let us simply decorate our customer class attributes with some data annotations

 

So what are we getting out of this ?  Run the project and see what change it brings to our database.

 

The Required Attribute made our column to be a not null column and the Max Length Attribute value become the size of the column.

 

2) Fluent API

Fluent API is another way to configure the Entitiy Properties or the relationship among the entities.   What we did with data annotations in the above example can be achieved with Fluent API as well. Why do we need to use Fluent API over Data Annotations or vice versa  ? Well , I guess it is more of a personal preference. Some people like to keep their classes clean. They just want to have the proeprty definition only in the classes and dont want to to define these attributes  in that class. Fluent API helps those people to keep these configuration in a different place.

Entity framework will generate the database by looking at the classes we have (not all the classes, but those classes which are using inside our DBContext class to create properties of type DBSet.) created. So There is a way we can override some of the configuration. There is an overridable method called OnModelCreating inside DBContext.  So we can override that in our DbContext class  to specify some of the configuration we want to apply when entity framework creates tables for us from the classes.

I am going to create another entity class to show this. Let us create a class called Address under our Model folder.  Add Properties like below to the Address entity.

Wait :  Include a rerence to  System.ComponentModel.DataAnnotations namespace in this class with a using System.ComponentModel.DataAnnotations statement.  We are going to use the data annotations present in this namespace in our class

Note that we did not add any data annotations to the properties of the Address class. So when we run the project, EF will create nullable nvarchar columns with MAX length for all those string properties.

Now To override the default configuration , Go to our DBContext class (SampleContext.cs) and add the below method.

Tip : You may simply type “override” inside the class and VisualStudio intellisense will show you all virtulal methods available to be overridden. Just select OnModelCreating from that.

We can now use the DBModelBuilder object which is an argument of this method, to configure our entity / entity properties.  Add some configurations in this method like below.

This code is pretty much self explanatory. It is saying that The Address Line1 Property of Address Entity should be Required field (not null) and should have a Max length of 100 (the column size). Run the project and see what output we are getting.

You can see that we are chaining methods here. That is something beautiful about this approach.

What if I have so many entities  ? I will have so much of code in this method and that is worse ! We dont want to do that. Wait !  there is a much better approach.  Little more refactoring ! We can move the configurations for an entity in a different class and just specify it in our OnModelCreating method. To show that, Let me add another class to our model folder called PhoneNumbers

Now to define the confiration ,  we will create another class called PhoneNumberConfiguration. We will inherit this class from EntityTypeConfiguration and specify the type while inheriting. In the Constructor we can define our configuration like this.

 

Now we will go back to our OnModelBuilder method and add the PhoneNumber configuration class instance to the Configurations property of modelBuider.

 

And you will see the results as

TIP : you need to include System.Data.Entity.ModelConfiguration namespace in your PhoneNumber configuration class as  EntityTypeConfiguration class belongs to that.

You can download the source code of this example here  for references.  Leave a comment if you download the source code from this page / this article helped you.

 

 

 

Starting Entity Framework Codefirst Approach Part- 1

Here is a small -quick-step -by-step  tutorial to get started with Entity framework code first approach. I have included the sample project at the end of this post for reference.

I created a new ASP.NET MVC3 Project using the New->Project Dialog.

In Code First Approach, We create our Entities first by writing classes. Then Entity framework will create the database for us based on our classes. So Let us create some classes.

Right click on the Models Folder and Select Add->New Item and Select Class. Give the class name as Customer.cs

Open the Customer.cs file and Add some properties for our Customer Entity.

OK. Now Let us create a controller and View

Right click on the Controllers folder in the Solution explorer and select Add->Controller. Give the Controller name as CustomerController. Keep the Scaffolding Template as Empty controller.

and we will add 3 action methods to this controller, The Index for Listing all customers and Create (both HTTPGET and HTTPPOST) for Creating new Entry.

Now Let us write some Data Acces code. right click on the project and Create a folder called “DAL” to store our data access code. Create a new class called “SampleContext” .

 

To make use of Entity framework, We need to have the entity framework dlls in our project. For adding that to our project, we can make use of Nuget package manager.

Right Click on the References and select “Manage Nuget Packages”. Select Entity Framework and click install. You may search in the search bar, if you don’t find Entity framework by default.

After the successful installation, you would see a green tick mark near to Entity framework.

Now if you expand the “References” section under your project, you can see EnrityFramework is added.

Lets go back to our SampleContext.cs file and make it inherit from DbContext. DbContext resides in System.Data.Entity namespace. So you need to add a using statement to refer that in your class.

Add a Property called “Customer” of type DbSet of our customer class


Now Go back to our Customer Controller and Replace the code like this

You can see that we are creating an object of SampleContext class and calling the Customers Property and applying the ToList() functions to convert the result as a List. When calling the Customers Property, Entity framework will return all customers stored in the table (which will be created).

I added some code in the Index view to iterate thru the Items and show it as an HTML table. You can find that in the sample project.

Now Let us run the Application by pressing F5 key. Browse to the Customer Index action. You may see a blank page because we don’t have any customer records present now.

Go to SQLExpress instance and there you can see a new Database called EFCodeFirst.DAL.SampleContext.

 

If you expand the tables you will see we have a table called Customers with all the columns same as our Customer classes properties.

By Default, Entity framework will create a databse in the local SQL Express instance. But you can override this in different ways. You can see taht the database name is the full name of our DbContext class with the Namespaces.. If you want to create a database with a different name, you can override it  by calling the DBContext base class constructor like this

 

To Add a new customer record, We can update our Create Action methods code like this

You can see that we are creating an object of our DbContext and adding a new Customer object to the Customers Property and Calling the SaveChanges method.  I am redirecting then back to the Index action to stick with the PRG (Post-Redirect-Get) pattern.

Since this is a small tutorial, I have everything in one project . When you start developing applications, you may split it into different projects for your entities and Data access layer. I will be writing more posts following this for making the code better and handling complex scenarios like Joins and datatype length etc..

You can download the source code of this example here for references.  Leave a comment if you download the source code from this page.

How to prevent jQuery mobile to style your form elements

If you are using jQuery mobile in your web page ( with their css ( default theme or whatever)), it will usually override your styles for input elements like this


But If you want to to ignore those styles offered by jQuery mobile and want to use the awesome styles your UI designer created, you can do that by simply adding data-role attribue to the input element with value set to “none”

If you are working with ASP.NET MVC3 razor, you can use this syntax

In this case it is the underscore instead of the dash. ASP.NET MVC will automatically convert this underscore to a dash when in render the Text box

 

The output will be your normal input box without any style

Sorry , my  UI Designer is on vacation ! :)

http://jquerymobile.com/download/

Entity Framework Code First- How to Avoid pluralized name in table creation

When you work with Entity Framework Code First approach, you are creating your database tables  from your model classes.  Usually Entity Framework will create tables with Pluralized names. that means if you have a model class called PhoneNumber, Entity framework will create a table for this class called “PhoneNumbers“. If you want to create table with singular name like Customer , you can do it like this

In your DBContext class,  Override the “OnModelCreating” method like this

 

Having this Method Overriding will avoid creating tables with pluralized names. Now it will create a Table called “PhoneNumber” , Not “PhoneNumbers”

Why I love CodeRush : Reason #1

This 3 Pictures will explain why is it so

Hover your mouse

Just a click

Entity Framework Code First– How to add a new Property to your model class with making an effect in your table structure

IF you are using Entity framework code first approach, there is a good chance that you will be adding new properties to your modal classes as your development goes further. As we know the “code-first” approach,  creates the database schema from your code ( your classes which represent your entities).  When you add a new property to your class, your tables are not in sync with your classes. because your schema is not updated. So running the project will give you an error like this

The Yellow screen of death while accessing the page in browser.

or while debugging in the IDE

image

What should we need to do to fix this problem ? Lets go back to our example and show what made Visual studio throw me this error.

 

This was my model class

 

public class ContactPerson : Person
{
public virtual ICollection<PhoneNumber> PhoneNumbers { set; get; }

}

 

My ContactPerson class is inherited from the Person class which looks like this

public abstract class Person
{
public int ID { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
public DateTime CreatedDate { set; get; }
public string FullName
{
get
{
return FirstName + ” ” + LastName;
}
}
}

 

So now I thought of adding a new property to the ContactPerson class so I added a new string property to my class like this

and now my modal class is not in sync with my database. That’s y I got the error when try to run the application.

 

To fix the error, We have to add a new class to our project.I will add this to my DAL folder.

add-new-initializer-class

 

I gave name as “CRMInitializer” and I in herited this class from “DropCreateDatabaseIfModelChanges<CRMContext>”.

My new class has nothing else in that. No methods or no properties or we didn’t even add a constructor

 

Now go to global.asax  and add the below line as the first line in your Application_Start method

 

Database.SetInitializer<OpenMVCRM.DAL.CRMContext>(new DAL.CRMInitializer());

 

So my updated Application_Start looks like this.

 

All set. Entity framework will add a new column to your table now.

Keep in mind that, this approach will drop the existing tables in the database and recreate those tables from scratch. That means you will loose all the data you already stored in the tables.

NUnit with ASP.NET MVC and CodeRush

Adding unit tests to your projects is one of the important thing in all the projects. Unit tests are the smallest testable parts of our application which ensures our code works as expected before we move to integrating our stuff into other modules or code. A unit test provides strict written contract that the piece of code should satisfy.

 

CodeRush is a Developer Productivity Tool from DevExpress.  I started using it a week ago and I should say its so cool.  You can download a 30 day trial version from here. I am using the same 30 day trial version now but hoping to get a licensed version in few days as I won one in a raffle happened in our local dot net user group monthly session.

 

Lets see how we will  handle unit tests with nunit in  an ASP.NET MVC project.

 

So I have an ASP.NET MVC project here.

image

 

To add a unit test project, simply right click on the solution and add a new class library project.

 

image

 

I will delete the default “Class1.cs” file because I don’t want any files in my solution which is of no use.

Now I will add a new class to this file called “ContatctControllerTest.cs”. This class will have test method to handle the ContactController in my ASP.NET MVC project.

Next is adding a reference to the project to be tested. So right click on the newly created test project and then select “Add Reference” and select the “Projects” tab.then select our MVC project and click OK button

 

image

Now we have the reference available under the “Reference” section of the test project.

 

image

 

Now we are going to use NUnit as our unit testing framework. So lets add the NUnit Dlls to our project. We are going to get his from the nuget repository using nuget package manager.

 

Right click on your test project and select “Manage Nuget Packages” from the context  menu.

 

image

 

Search for nunit and install that.

 

image

 

Then I added a reference to  System.Web.MVC dll in my test projects because we will be using some classes in that assembly.

 

Now we will set the path to nunuit dlls in coderush options window so that coderush can take care of the rest for us.

Go to Tools->DevExpress->Options and Select UnitTesting and set the path to binaries

 

image

 

 

Now we can create a class called “ContactControllerTest.cs” and put this code inside that

 

using System.Collections.Generic;
using NUnit.Framework;
using OpenMVCRM.Controllers;
using OpenMVCRM.Models;
using System.Web.Mvc;

namespace OpenMVCRM.Tests
{
    [TestFixture]
    class ContatControllerTest
    {
        [Test]
        public void TestContactList()
        {
            ContactController c=new ContactController();
            var result = c.Index() as ViewResult;
            Assert.AreEqual("Index", result.ViewName);
        }
      
    }
}

 

Now right click on the test method and select “RunTests”

 

image

 

and you can see the results in the output window

 

image

 

One Good think I like about code rush in this scenario is , once you run your tests, code rush will show the status of the test near to the method.

image

 

If you hover your mouse over, you will see a tool tip saying “Test has passed”. Its so awesome.

image

Output caching in ASP.NET MVC3 Actions with ActionFilters

How do we do OutPut Caching in ASP.NET MVC3 ?

We haven an ActionFilter called “OutputCache” which we can apply on our controller action methods to achieve this.

Just mention this attribute above your ActionMethod.

the above code will cache the action method called “CachingTest” for 10 seconds.

 

 

 

How to get Add View/ Add Controller menus in Solution explorer when converting existing ASP.NET web for project to MVC

So you heard about (that wonderful and addictive) ASP.MET MVC and started thinking to jump into that by converting your existing ASP.NET web application to ASP.NET MVC ? There are plenty of tutorials available online to help you in that .Scott gives step by step instruction in this tutirial. I also followed this link to do the same. One thing i found missing is , Scot did not mention in his post how to fix the issue of “Add View/ Add Controller menus”  not appearing when you right click on the Controller/ View folders. I just want to show that here.

 

The reason why the menus are not coming is visual studio IDE do not consider this as a real ASP.NET MVC project because the project file does not say so. So we should update the project file to include the project type guid  for ASP.NET MVC and then the IDE willl start supporting the menus specific for ASP.NET MVC type project.

 

Step 1

Go to your solution explorer and unload the existing ASP.NET project by right clicking and selecting “Unload Project

Step 2

Right Click the Project in solution explorer and select “Edit your project file name

Step 3

 

Go to the Element called “ProjectTypeGuids” and Add “{E53F8FEA-EAE0-44A6-8774-FFD645390401};” infront of the existing content.

Before Adding

After Adding

And We are all set to go and rock

I would love to know how many of you went back to web forms after working  on an MVC project ?  i will buy a coffee for you if your answer is yes.

 

I Lost !

Please wait till i restore my old blog backup.