Entity Framework 6.0 Code First

Introduction

In this article, we will learn the basics of the Entity Framework Code First approach by creating a simple console application, but are new to Entity Framework. Here I will explain how to create an Entity Framework 6.0 application using the Code First approach.

Code First approach

The Code First Approach is an alternative way to the Database First and Model First approaches to the Entity Data Model and creates a database based on our classes that we will be creating in this article. Using those classes we are creating an entity data model.

  1. Creating the Application

    You will need to have Visual Studio 2010 or Visual Studio 2012 installed and SQL Server 2012.

    1. Open Visual Studio 2010 or 2012.

    2. File -> New -> Project.

      create new project in asp

    3. Select Windows on the left side then seelct Console Application.

    4. Name the project, here I named it CodeFirstDemo.

    5. Click on OK.

      new console application

  2. Creating a Model with Code First

    In this we use code first to create a new database using the code first model. Here we create two entities or classes Employee, Company, Department and CompContext. Using these classes we create a table structure as follows.

    Employee.cs
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. namespace CodeFirstDemo  
    5. {  
    6.       class Employee  
    7.       {  
    8.             public int EmpID { getset; }  
    9.             public string EmpName { getset; }  
    10.             public string City { getset; }  
    11.             public int ContactNo { getset; }  
    12.       }   
    13. }  
    Department.cs
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. namespace CodeFirstDemo  
    5. {  
    6.       class Department  
    7.       {  
    8.             public int DeptID { getset; }  
    9.             public String DeptName { getset; }  
    10.       }  
    11. }  
    Company.cs
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. namespace CodeFirstDemo  
    5. {  
    6.       class Company  
    7.       {  
    8.             public int CompID { getset; }  
    9.             public string CompName { getset; }  
    10.             public String Location { getset; }  
    11.       }  
    12. }  
  3. Creating a Context

    The domain classes described above have nothing to do with the Entity Framework. They have no knowledge of it, that's the beauty of working with Code First. You get to use your own classes. To use Code First, you start by defining a class that inherits from DbContext.

    1. Right-click on Project then select Manage NuGet Packages.

      Note:
      If you don't have the Manage NuGet Packages option you should install the latest version of NuGet.

      manage Nuget package

    2. Select the Online tab.

    3. Select the EntityFramework latest version package.

    4. Click Install.

      entityframwork

      Add the class defined above in that context as follows.

      CompContext.cs
      1. using System;  
      2. using System.Collections.Generic;  
      3. using System.Data.Entity;  
      4. namespace CodeFirstDemo  
      5. {  
      6.       class CompContext : DbContext  
      7.       {  
      8.             public DbSet<Employee> Employees { getset; }  
      9.             public DbSet<Department> Departments { getset; }  
      10.       }  
      11. }  
      When you inherit the DbContext class you got the error like the following:

      codefirst code

      For that add the following using statement.
      1. using System.Data.Entity; 
  4. Reading and Writing data to database.

    In all the code above we need to store and retrieve data from the database. This code creates a new instance of our context and then uses it to insert a new Employee.

    Program.cs
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. namespace CodeFirstDemo  
    5. {  
    6.     class Program  
    7.     {  
    8.         static void Main(string[] args)  
    9.         {  
    10.             using (var context = new CompContext())  
    11.             {  
    12.                 //Storing data in Database  
    13.                 context.Employees.Add(new Employee { EmployeeID = 1, EmpName = "Krishna Yadav", City = "Mathura" });  
    14.                 context.Employees.Add(new Employee { EmployeeID = 2, EmpName = "Jeetendra Gund", City = "Daund" });  
    15.                 context.Employees.Add(new Employee { EmployeeID = 3, EmpName = "Pravin Kumar Singh", City = "Banglore" });  
    16.                 context.Employees.Add(new Employee { EmployeeID = 4, EmpName = "Anand Bhave", City = "Mathura" });  
    17.                 context.Employees.Add(new Employee { EmployeeID = 5, EmpName = "Pranav Joshi", City = "A. Nagar" });  
    18.                 context.Employees.Add(new Employee { EmployeeID = 6, EmpName = "Makrand B", City = "Akluj" });  
    19. context.SaveChanges();  
    20.                 //Retriving data from Database  
    21.                 var query = from b in context.Employees  
    22.                             orderby b.EmpName  
    23.                             select b;  
    24.   
    25.                 foreach (var item in query)  
    26.                 {  
    27.                     Console.WriteLine("Employee Name : " + item.EmpName + " City : " + item.City);  
    28.                 }  
    29.   
    30.                 Console.WriteLine();  
    31.                 Console.WriteLine("Press Any key to exit...");  
    32.                 Console.ReadKey();  
    33.             }  
    34.         }  
    35.     }  
    36. }  
    Result:

    output

  5. Where's the data coming from?

    Here DbContext has created the database for you. If a local SQL Express is present then Code First creates the database on that instance. The database name is the fully qualified name of the derived context like this, CodeFirstDemo.CompContext.

    You can connect to the database using Server Explorer in Visual Studio:

    1. Select View -> Server Explorer.

      server explorer

    2. Right-click on Data Connection then select Add New Connection.

      database refresh

    3. Enter Server Name (localdb)\v11.0 and Database Name CodeFirstDemo.CompContext.

    4. Click OK.

      server name

    5. The Server Explorer will look like the following:

      compaines

  6. Check that the data is inserted into the SQL Server 2012.

    1. Open SQL Server Management Studio.

    2. Click on Object Explorer.

    3. Click on Connect to server.

    4. Enter server name (localdb)\v11.0.

      localdb

    5. Click Connect.

      codefirst demo

    6. Check the data in the database. Select query for Employee.

      sql query

      Output:

      query output

Note: For detailed code please download the Zip file attached above.

Summary

I hope you now understand Entity Framework Code First. If you have any suggestion regarding this article then please contact me.


Similar Articles