Code First Approach in Entity Framework

Introduction

 
In simple terms, the Code First approach in Entity Framework is a way of creating a database and its tables using C# code and Entity Framework classes. For this approach, we will first consider the tables for storing the data, then we will design the classes depending on requirements. In these articles, I will show you in very simple ways and I hope you will be able to understand all the concepts.
 
Important for you
 
Before learning we will first consider the classes very important for the Code First approach:
  1. DBContext
  2. DBSet
I will explain in very few words, if you want to learn more about DBContext and DBSet then Click.
 
But don’t think this class isn't used in the Database First approach and Model First approach. It is used but you don't care about these classes.
 
DBContext
  1. It works to convert a LINQ to Entity query to a SQL query and send it to the database.
     
    Note: Please don't be confused about the entity. “An entity is a class defined for mapping into a table.” If you are confused about what an entity is then don't worry, I will explain it in a very simple way with an example.
     
  2. It does insert, update, and delete operations on the database based on the entity.
     
  3. It keeps track of changes that occurred in the entities after it has been retrieved from the database.
DBSet
 
The DBSet class represents an entity set to create, read, update, and delete operations.
 
Now let’s do it.
 
Step 1
Go to "File" -> "New" -> "Project..." and add a console application.
 
console application
 
Step 2
Now right-click on the References folder and use the NuGet package for installing the Entity Framework DLL. If you do not have NuGet then download the Entity Framework DLL from Google and add to the references folder.
 
NuGet
 
Step 3
Now look into your references folder and find the Entity Framework DLL as in the following:
 
references
 
In the preceding image the second highlighted assembly is for annotation. This is essential for you. If it's is not available then add it from the .Net assembly.
 
Right-click on the references folder then click on Add reference then in the .Net tab choose it.
 
Step 4
Now add two class named "Employee" and “Department”.
  1. using System.ComponentModel.DataAnnotations;  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3.   
  4. namespace CodeFirstApproachInEntityFramework  
  5. {     
  6.     public class Employee  
  7.     {  
  8.         [Key]  
  9.         public int EmployeeID { getset; }  
  10.         public string Name { getset; }  
  11.         public int Age { getset; }  
  12.         public string Gender { getset; }  
  13.         [ForeignKey("Department")]  
  14.           
  15.         public int DepartmentID { getset; }  
  16.   
  17.         public Department Department { getset; }  
  18.   
  19.     }  
  20. }  
  21.   
  22. using System.ComponentModel.DataAnnotations;  
  23. using System.ComponentModel.DataAnnotations.Schema;  
  24.   
  25. namespace CodeFirstApproachInEntityFramework  
  26. {     
  27.     public class Department  
  28.     {  
  29.         [Key]  
  30.         public int DepartmentID { getset; }  
  31.         public string DepartmentName { getset; }  
  32.   
  33.   
  34.     }  
  35. }  
code
 
Annotation
 
Annotation provides constraints on classes and properties like [Key].
 
[Required],[MaxLength(50)], here the [Key] attribute maps into the database as a Primary key for the EmployeeID and DepartmentID coloumns.
 
For Foreign Key you use System.ComponentModel.DataAnnotations.Schema namespace.
 
Step 5
Now add a new class and provide the name "EmployeeContext" as in the following:
 
EmployeeContext
 
Step 6
Add an App.Config file and add a connection string as in the following:
  1. <connectionStrings>  
  2.    <add name="DBCS" connectionString="SERVER=piyush-pc;DATABASE=EntityDB;USER ID=sa;PASSWORD=pass.123" providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  
Note: Before running this program you need to create a database named EntityDB.
 
Step 7
Now write the following code in the console application.
  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace CodeFirstApproachInEntityFramework  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.   
  11.             using (EmployeeContext cx = new EmployeeContext())  
  12.             {                 
  13. // Here i going to insert data into department table because it is
  14. //referenced by a FOREIGN KEY constraint And we are already know that
  15. //Employee data will be not inserted into Employee table until we doesn't   
  16.                 //insert data into Department table  
  17.   
  18.                 ////Now I am going to insert data into Employee table  
  19.                
  20.                 IList<Department> department = new List<Department>   
  21.                 {  
  22.                     new Department{DepartmentID=1,DepartmentName="IT"},  
  23.                     new Department{ DepartmentID=2, DepartmentName="HR"},  
  24.                     new Department{ DepartmentID=3, DepartmentName="Account"}             
  25.                 };  
  26.                 cx.Departments.AddRange(department);  
  27.                 cx.SaveChanges();  
  28.                 ////Now I am going to insert data into Employee table  
  29.   
  30.                 Employee employee = new Employee();  
  31.                 employee.EmployeeID = 1;  
  32.                 employee.Name = "Mohit";  
  33.                 employee.Age = 21;  
  34.                 employee.Gender = "Male";  
  35.                 employee.DepartmentID = 1;  
  36.                 cx.Employees.Add(employee);  
  37.                 cx.SaveChanges();  
  38.                  
  39.                 Console.WriteLine("Tables have created successfully.");  
  40.             }  
  41.             Console.ReadKey();  
  42.         }  
  43.     }  
  44. }  
Note: Here I am not handling the primary key conflict sinice if you insert employeeID=1 again then it will throw an error.
 
Step 8
After successfully running, go to SQL Server Management Studio and open your EntityDB database and look.
 
EntityDB
 
So in the preceding I attempted to explain everything in a very easy way. I hope you enjoyed it.