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 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 the 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 the following structure.

Code first approach in entity framework

Steps for the remainder of this demo

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".

Entity framework

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 { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Mobile { get; set; }
    }
}

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 of 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 { get; set; }
    }
}

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 the 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 select Add > Controller use the name "StudentController" and make the following selections as shown in the image below.

Click on add

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

Student details

Let's run the project. You will get an error page as given below; this is because the application is expecting a "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.

The resource cannot be found

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

Student controller

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 with "student". Now run the application again, you will not see that error page anymore.

If you are interested in 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, that if you want to validate your data before sending it to the database you want to define any validation expression or want to make any field "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:

Add some validation

If you run the application here, you will get an error message.

Error message

This class file directly represents the database table's structure, and making any changes here is the subject of 'Code First Migrations' to update the database and its tables, and that is why you got the 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 the next step, 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 the Global.asax file and make the following changes.

Globalasax

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

Enter minimum 3 or maximum 10 chars

Step 8. Looking at Database

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 your database files.

Looking database

Now the question is how to change the database instance name, this is so 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.

Database name

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

Websites

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 my YouTube channel here http://www.youtube.com/user/abhimanyukumarvatsa.

I hope you like this article.

Thanks.