Code First Approach in Entity Framework


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

What is Code First Approach?

Code First Approach provides an alternative to the Database First and Model First approaches to the Entity Data Model and creates database of 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.

Follow the steps for the rest part 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 NuGet Package window, type 'Entity Framework' in search box and click to install it. After installation you will notice a new library file in References Folder 'EntityFramework'.

Step 2: Adding Classes

Right click on the Models Folder to add a new class file named 'Student.cs' and type following codes.

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 above properties by inheriting DbContext. Note to use a namespace System.Data.Entity.

Step 2: Adding DbContext

Right click on the Models Folder to add a new class file named 'StudentContext.cs' and type following codes.

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 lots of things for us like it will create database and tables. You can check your newly added database file.

Step 3: Adding Controller and Views

Build the solution here by menu Build > Build Solution because I want Model class and Data context class to be popped up for me in Add Controller window. Go ahead to add a controller for this right click on the Controllers Folder in the Solution Explorer and select Add > Controller and use the name 'StudentController' and make following selections as given in image below.

Now, everything setup and ready for us including controller and its different views.

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

For now request 'student' controller using url something like http://localhost:portnumber/student and try to perform CRUD operation.

Everything is functioning well so far.

Step 4: Routing Application

When you run the application, you will get error page at very first hit, because the application is expecting 'Home' as a controller by default but we don't have '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 'App_Start' folder and make a single change.

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

Just replaced the controller value to 'student'. Now run the application again, you will not see that error page anymore.

Step 5: Data Validation Using Data Annotations

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

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

Because, this class file directly representing 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 lose, hoping to see such functionality in coming releases. Let's move to next step to do database migration.

If you want to learn more on 'Data Validation Using Data Annotations', please read here

Step 6: Database Migration

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

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

You will notice above defined validations are working now, image give below.

If you want to learn more on 'Code First Database Migration', please read here

Step 8: Looking at Database

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

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

Step 7: Change Database Name Instance

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

Open 'StudentContext.cs' file and make following changes.

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

Download the source code from here.

Find a very nice video on this title by Julie Lerman here

I have done couple of video posts on MVC basics, if you are interested go and watch at my YouTube channel here

Video Version of this post (in Hindi Language):-

I hope you like this post. Thanks.


  1. Good work man, this was simple, clear and good explanation of Entity framework i have came across.

    By any chance did you work on DB First approach.


    1. Thanks Patel.

      Yes I posted DB First title today

  2. Good work! Nice and precise!


  3. Thanks Abhimanyu..This tutorial is helpinglot.....

  4. did you work on model first approach?

  5. Hi great tutorial thanks! I tried to follow it using Visual 2010 and MVC 3, I had the following problem "The provider did not return a ProviderManifestToken string" searching a solution I discovered I have no defined no connection string when I added one all works, I have no DB defined in AppData folder is this due to me using MVC 3 and not MVC 4 ?

  6. where is database connection string. How application read which database i can connect.

    1. you can always find it in web.config. EF connection string is bit different from normal db connection strings.

  7. Thanks Abhi,
    This is really simple to understand

  8. Abhimanyu, this is really great to see your tutorial. I think you will go very long. Keep it up...

  9. Thanks Abhi,

    Looking forward for more such stuff related to ASP.NET MVC.......

  10. Thanks Abhimanyu,

    Really a good article to understand the code first approch.Please suggest me that can we use this approach in a fresh NopCommerce application?

  11. Hi Abhimanyu Sir,

    How it is possible when my class has some change and after migration of database then its table data should not be lost.

    1. Every time you make changes in conceptual model (database model), use migration always to update database and safeguard your previous records.

  12. Thanks Abhimanyu,

    In my projects I use Code First to an Existing Database approach so the Code First creates a code based model that maps to an existing database using reverse engineering code first.
    but I got stuck when I changed the database updating or adding some column and I don't know how to update my classes in the project.


  13. Hi Abhimanyu,
    I am very new to MVC and like to learn. I have created the project as above. But when I click CreateNew it gives me this error:
    CS0103: The name 'Scripts' does not exist in the current context

    Can you please help?

    Thank you

    1. You need to add in View's web.config file like below

      <add namespace="System.Web.Optimization" />

    2. Thank you very much it is working.

  14. Heloo sir I have Created Project as suggested by you. Project Works Fine

    But i am not able to see the database in the App_data folder in fact that folder it self is not available in the Project

    What to do where to find the Database please help me !!!

    1. hi,

      It will be visible to you once you will to the App_Data folder in your drive. Not through the Solution Explorer.

      ~ Regards,
      Kush kant dayal | Pune

  15. Database.SetInitializer(new DropCreateDatabaseIfModelChanges());

    The above code will drop the database when we change the model, instead of this approach use package manager console to enable Migrations

    following code will enable the Migrations and update the database without loosing data.

    PM> Enable-Migrations -ContextTypeName Code_First_Approach_in_Entity_Framework.Models.StudentContext

    PM> Add-Migration Name

    PM> update-database

  16. Hi Abhimanyu sir, which approach is better according to u if we want to use entity framework?

  17. Hii , Abhi Sir ,

    Very good post and it work very well and very well explained !! I have done migration by enabling the Migration in the Package Manager Console..

    Can you tell me how to rename column in the Database using the Package manager Console ???

    Waiting for your reply.GD !

  18. thank you very much , that's so helpful , i'm a beginner in .NET and c# :D

  19. If you are going for finest contents like I do, simply pay
    a visit this site daily since it gives quality contents, thanks

    My blog easy paycheck formula scam

  20. hi
    I had doubt is this code will effect in the local data base means we have inserted number of employees list is this reflect in local data base or not and i did this example but data base was not created in the local server
    and my question is how to update this created Student
    controller in the local database

  21. Hi Abhimanyu,

    It's really very short,simple,quick and easy learning. Great stuff.
    I have one issues while using this approach it getting error, "add-migration error: "model backing the context has changed" and "The model backing the ... context has changed since the database was created".
    To short this problem out, I used the following line in my context class..
    Database.SetInitializer(new DropCreateDatabaseIfModelChanges());
    where my MyProjectDBContextClass is my ContextClass.
    Now again it comes with another error..
    "Additional information: Cannot drop database "CodeFirstDB" because it is currently in use."

    Would you like to give any reply to me on that at [email protected] .

    Thanks Avhi.

  22. I am not able to add StudentController . it giving me error

  23. unable to add give the following error
    unable to retreive metadata for mvcapplication8.models.student..unable to cast of type 'system.Data.Entity.Objects.Objectcontext' to type 'System.Data.Objects.ObjectContext'

  24. Sir if i do not Add Migration in project

  25. Thanks alot Abhimanyu Kumar Vatsa this article helps me alot..

  26. HI,
    i don't now any thing in Mvc just Beginner code first approch connection string is needed or not ?


Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples