Code First Approach in Entity Framework

Introduction

Entity Framework is the Microsoft preferred method of data access for .NET applications. It supports strongly-typed access through LINQ. Entity Framework also allows developers to program against a conceptual model that reflects application logic rather than a relational model that reflects the database structure. Entity Framework can be used from an ASP.NET Application, (using Entity Data Source) or in ASP.NET MVC etc. In this article we will be creating this using MVC App and we'll be using Visual Studio 2012 for the demo.

What is Code First Approach?

The Code First Approach provides an alternative to the Database First and Model First approaches to the Entity Data Model and creates a database for us based on our classes that we will be creating in this article.

Demo MVC Application

Create a new ASP.NET MVC Project by New > Project > ASP.NET MVC 4 Web Application > Empty Template; you will get following structure:

1 (1).png

Use the following steps for the remainder of this demo.

Step 1: Adding NuGet Package (if not available in references)

Right-click on the References Folder and select "Manage NuGet Packages". Alternatively you can install it from Tools > Library Package Manager > Package Manager Console and type "Install-Package EntityFramework". Okay, let's do this from a NuGet Package window; type "Entity Framework" into the search box and click to install it. After installation you will see a new library file in the References Folder "EntityFramework".

2.png

Step 2: Adding Classes

Right-click on the Models Folder to add a new class file named "Student.cs" and type the following code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;
 

namespace Code_First_Approach_in_Entity_Framework.Models

{

    public class Student

    {

        public int StudentID { getset; }

        public string Name { getset; }

        public string Address { getset; }

        public string Mobile { getset; }

    }

}

So, I have declared four properties: StudentID, Name, Address and Mobile. Now go ahead and create a class to manage the link with the database the above properties by inheriting DbContext. Note to use the namespace System.Data.Entity.

Step 3: Adding DbContext

Right-click on the Models Folder to add a new class file named "StudentContext.cs" and enter the following code:

using System;

using System.Collections.Generic;

using System.Data.Entity;

using System.Linq;

using System.Web;
 

namespace Code_First_Approach_in_Entity_Framework.Models

{

    public class StudentContext : DbContext

    {

        public DbSet<Student> Students { getset; }

    }

}

Now, this DbContext will do many things for us such as it will create databases and tables. You can check your newly added database file.

Step 4: Adding Controller and Views

Build the solution here by menu Build > Build Solution because I want Model class and Data context class to be available for me in the Add Controller window. Go ahead and add a controller; to do that right-click on the Controllers Folder in the Solution Explorer and select Add  > Controller and use the name "StudentController" and make the following selections as shown in the image below:

3.png

Now, everything is setup and ready for us including the controller and its various views.

4.png

Let's run the project. You will get an error page as given below; this is because the application is expecting "Home" controller by default and we don't have this controller instead we have a "student" controller. You will see how to fix this in the next step.

5.png

For now request the "student" controller using an URL something like http://localhost:portnumber/student and try to perform CRUD operation.

6.png

Everything is functioning well so far.

Step 5: Routing Application

When you run the application, the very first thing you will get is an error page, because the application is expecting "Home" as a controller by default but we don't have a "Home" controller in our application instead we have "Student" so we need to modify the default hit by the application. For this, find a file "RouteConfig.cs" in the "App_Start" folder and make a single change.

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "student", action = "Index", id = UrlParameter.Optional }
);

The only change is just to replace the controller value to "student". Now run the application again, you will not see that error page anymore.

If you are interested to learning more about Routing, then go ahead and learn it from ScottGu's blog post here:

http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx 

or http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx.

Step 6: Data Validation Using Data Annotations

Assume, if you want to validate your data before sending it to the database or you want to define any validation expression or want to make any field as "Required". For this we can take advantage of  the 'System.ComponentModel.DataAnnotations.dll' assembly shipped with the MVC package and you can find it in the References folder. Now to enable the validation, open the "Student.cs" model and add some validation lines, as in:

7.png

If you run the application here, you will get the error message:

8.png

Because, this class file directly represents the database table's structure and making any changes here is subject of 'Code First Migrations' to update database and its tables and that why you got above error. Remember, you will lose all your records if you migrate your database here. Still Microsoft is working on this subject to avoid data loss, hoping to see such functionality in coming releases. Let's move to next step to do database migration.

If you want to learn more about "Data Validation Using Data Annotations" then please read: http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs.

Step 7: Database Migration

Now, don't worry about data loss here and go ahead to update the database table to test the preceding validation rules.

For this, open Global.asax file and make the following changes:

9.png

You will see that the above defined validations are working now; the image is given below.

10.png

If you want to learn more about "Code First Database Migration" then please read: http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx.

Step 8: Looking at Database

So, now if you want to see where the database has been created for this app. Open the directory where you have created your app and open the App_Data folder; you will find you database files.

11.png

Now the question is how to change the database instance name, this is soo long here. Let's learn it in another step.

Step 9: Change Database Name Instance

In the above image you will see our default database name is "'Code_First_Approach_in_Entity_Framework.Models.StudentContext". Let's change it. Remember you will again lose your records.

Open the "StudentContext.cs" file and make the following changes:

12.png

Now, again check the 'App_Data' folder, you will notice new database files have been created.

13.png

Find a very nice video on this title by Julie Lerman here http://msdn.microsoft.com/en-us/data/gg715119.

I have done a couple of video posts on MVC basics, if you are interested go and watch at my YouTube channel here http://www.youtube.com/user/abhimanyukumarvatsa.

I hope you like this article. Thanks.

Up Next
    Ebook Download
    View all
    Learn
    View all