Entity Framework Code First Example

As we all know, Entity Framework is an enhancement to an existing ADO.Net technique and ORM framework we used for Microsoft technologies.

There are the following 3 approaches we use during application development:

  1. Code First
  2. Model First
  3. Database First (DB first)

So, in this article we will learn how to develop a simple C# application using the Entity Framework code first approach.

You need Visual Studio 2010/2012/2013 and SQL Server to learn this.

Create a new C# Class Library project named "CodeFirstLibrary". Add a new class named "Employee" to the project. (You can use Entity Framework 4.1/4.3/5.0/6.0 for this example.)

Employee Class

  1. public class Employee   
  2. {  
  3.     public Employee ()  
  4.     {   
  6.     }  
  7.     public int EmployeeID { getset; }  
  8.     public string Name { getset; }  
  9. }    

Add a new class derived from the DBContext class with a DbSet property for the Employee class.

(References needed: System.Data.Entity and EntityFramework).

  1.  public class Context: DbContext   
  2.  {  
  3.      public Context(): base()  
  4.      {  
  6.      }  
  7.      public DbSet<Employee> Employees { getset; }  
  8.  }         

Add a new console application project named "CodeFirstConsole" to this solution so that we can test these classes:

  1. using (var ctx = new Context())  
  2. {  
  3.     Employee emp = new Employee() { name = "Prashant" };  
  4.     ctx.Employees.Add(emp);  
  5.     ctx.SaveChanges();                  

Set "CodeFirstConsole" as the startup project. Run the application and see what is happening. It has successfully stored the Employee information into the database.


Where is the database? How was it created? What are the tables created, what is the table structure?

This is the beauty of Code First for the Entity Framework. It creates the database based on a parameter passed in the base constructor of your context class. We have not passed any parameters so it will create a “CodeFirstLibrary.Context” database in the local SQLEXPRESS.

Some Important points to note here are:

  1. Code-first will create a table in the database. The "Employees’ table is created based on the Employee class.

  2. Code First APIs create a PrimaryKey in the table if the class has either an “Id” or ClassName + “Id” property. For example, the Employee class has the “EmployeeID” property so it will create EmployeeID as the PK column.

  3. It will also create other columns with the same name and datatype as property names as shown in the following screenshot.

So, using EF Code First, we can create applications that will generate a DB at runtime.

Similar Articles