Entity Framework - CodeFirst Model

Posted by in .NET Framework category on for Beginner level | Points: 250 | Views : 42311 red flag
Rating: 4.75 out of 5  
 4 vote(s)

Entity Framework supported the development of applications using Schema first and Model First approach. Now, the new Entity Framework introduced the Code First approach.

Entity Framework

Entity Framework supported the development of applications using Schema first and Model First approach. Now, the new Entity Framework introduced the Code First approach. In Code First approach, we are creating the code first and the Entity framework will automatically generate the corresponding tables. Let us discuss more about Code First approach of Entity Framework here.


NuGet is a Visual Studio extension that makes it easy to install and update open source libraries and tools in Visual Studio. We will use NuGet to get the Entity Framework installed. The advantage here is that the associated assemblies will be added to the project automatically.

You can install the NuGet either from http://www.nuget.org/ or using the Extension Manager in Visual Studio 2010 IDE.

Install Entity Framework

After installing NuGet, create your application. Right click on the References and choose Add Library Package Reference option.



Select Online and Search for EntityFramework. Select Install to install the Entity Framework.


This will add the assemblies required by the Entity Framework to your application.

Create the Classes

Now Let us create the classes required for our project. For our sample, I am using two classes Student and Marks. Each student will have a list of Marks associated with it.

public class Student


        public int Id { get; set; }

        public string FirstName { get; set;} 

       public string LastName { get; set;}

        public List<Mark> Marks { get; set; }


public class Mark


        public int Id { get; set; }

        public string Subject{ get; set; }

        public int mark { get; set; }



CodeFirst depends mainly on the DbContext. DBContext automatically generate the database using the tables defined. We will define our DbContext as


public class MyDbContext: DbContext


        public DbSet<Student> Students { get;set; }

        public DbSet<Mark> Marks { get;set; }     }


Define Data Access Methods

Now let us define a class with data querying methods. For our sample, we use the StudentData class with a GetStudents method to retrieve the data from the DbContext.


public class StudentData


        MyDbContext context = new MyDbContext();

        public List<Student> GetStudents()


            return (from s in context.Students

               select s).ToList();




Define Connection String

Now we need to define the connection string to connect to the database. DbContext will use this connection string to generate the Database and associated tables from the code.

   	<add name="MyDbContext"
        connectionString="datasource=.;Integrated Security=SSPI; database=Students"
        providerName="System.Data.SqlClient" />

Normally, we will specify the connection string name as DbContext name; but we can use a different name too.

Define the UI

Build the solution. Building the solution is important; otherwise when we try to define a datasource pointing to the Object, our StudentData object will not be available.

Now, let us define the UI to display the data. For our sample, I am having one GridView with a DataSource associated with it. Configure the datasource using our StudentData, which return the Student data as a list.

Select the StudentData defined in the project.


Now, select method used to return the student details.


Run the application

You can observe a blank page. Now, DbContext created the database and tables in the specified server. Let us open the server explorer and verify the same.


You can observe that, there is a new database with name Students is created in the server. You can observe the two tables created under the table – Students & Marks.


You can notice the foreign key generated as part of the Marks table. Also the id fields are generated as identity fields.

There is another table generated with the name EdmMetaData, which will be for tracking the changes. We will discuss about it in latter.

Let us enter some data to the Students table.

Now we will run our application again.


In this article we discussed about the new model of Entity Framework – CodeFirst. We will look more on the Entity Framework and its capabilities latter.


Please find the Solution structure used for constructing the sample Code First project.




Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Ambily KK
Member Level: Silver
Member Status: Member,Microsoft_MVP,MVP
Member Since: 5/18/2010 1:05:25 AM
Country: India
Thanks Ambily K K http://ambilykk.com/
I have over 9 years of experience working on Microsoft Technologies. I am carrying the passion on Microsoft technologies specifically on web technologies such as ASP .Net and Ajax. My interests also include Office Open XML, Azure, Visual Studio 2010. Technology adoption and learning is my key strength and technology sharing is my passion.

Login to vote for this post.

Comments or Responses

Posted by: A4u6178 on: 5/13/2011 | Points: 25
hi madam,

I am beginner, i read the article its very good .

I have some queries to ask about classes.. hope u revert back soon..

1. Are student and mark classes in same C# file which we add by using add new item option .
2. where this MyDbcontext class code written ? Is another C# file or same file in which student & mark are present
Posted by: Ambily.raj on: 5/15/2011 | Points: 25

Answer for your queries
1. You can place both Student and Mark inside same cs file. But, for better maintainability, place this into two cs files.
2. MyDBContext is a custom class derived from DBContext, which will be responsible for generating the database and tables from code. This class can be placed in a single file or different file.

Please refer the Solution structure updated at the end of the article.

Posted by: A4u6178 on: 5/16/2011 | Points: 25
Thank You very much for the updates..
Posted by: Maheshvishnu on: 9/5/2012 | Points: 25
In Connectionstring you mentioned Database name as Students

but in Server explorer tables are created in ambily database?

My doubt is how can i map the tables created throgh code first approach to particular database.

Login to post response

Comment using Facebook(Author doesn't get notification)