A Simple Step to Entity Framework: Code First Approach

Introduction

 
The Entity Framework is an Object Relational Mapping (ORM) providing an automated mechanism for CRUD operations to a database.
 
Entity Framework provides various approaches like:
  • Database first
  • Model First
  • Code First
This article explains the Code First approach. This is mainly used for domain driven development. Initially we are not focusing on the database development, so we are creating classes instead of tables in the database. Based on these classes we can simply create our database.
 
A quick start
 
1. Create a console application:
 
 
2. Add a new class:
 
 
3. Class name as Employee:
 
 
4. Write the field names in the Employee table (consider this Employee class is your Employee Table):
 
 
5. Go to the project References => Manage NuGet Packages.
 
 
6. Install EntityFramework:
 
 
7. Return to our Employee class and add the reference:
  1. using System.ComponentModel.DataAnnotations;  
ComponentModel.DataAnnotations
 
Provides attribute classes to define metadata for ASP.NET MVC and ASP.NET data controls.
 
System.ComponentModel.DataAnnotations Namespace.
 
Some examples
Table
Table Name
Column
Column name
Key
PK for the table
ForeignKey
FK Relation
Required
Required field validation
MinLength
Min length of the field
MaxLength
Max Length
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.ComponentModel.DataAnnotations;  
  7.   
  8. namespace CodeFirstSampleAp  
  9. {  
  10.    public class Employee  
  11.     {  
  12.   
  13.        public Employee()  
  14.        {  
  15.   
  16.        }  
  17.   
  18.        [Key]  
  19.        public int EmpID { getset; }  
  20.        public string EmpName { getset; }  
  21.        public string Address { getset; }  
  22.     }  
  23.   
  24. }  
Add a new class MyContext and inherit the DbContext with a "using" for the reference as in the following:
 
using System.Data.Entity;
 
 
Next, we need to plan where we need to create our database. So in the app config create our connection string.
 
  1. <connectionStrings>  
  2. <add name="MydbConn"   
  3. connectionString="Data Source=.;Initial Catalog=CompanyDB;Integrated Security=true"   
  4. providerName="System.Data.SqlClient"/>  
  5. </connectionStrings>  
Then return to our MyContext class and pass our connection details here.
 
Also, we can plan our database Initializer. That means all the time we don't want to create a new database. Based on our requirements we can plan this.
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace CodeFirstSampleAp  
  9. {  
  10.     public class MyContext : DbContext  
  11.     {  
  12.   
  13.        public MyContext()  
  14.             : base("MydbConn")  
  15.        {  
  16.            Database.SetInitializer<MyContext>(new CreateDatabaseIfNotExists<MyContext>());  
  17.              
  18.        }  
  19.   
  20.      public  DbSet<Employee> Employees { getset; }  
  21.   
  22.     }  
  23. }  
More options for the database Initializer:
 
 
Suppose we are working with a production db, so we can prevent or turn off this feature.
  1. Database.SetInitializer<MyContext>(null);  
Next go to main and add a value to our new table:
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace CodeFirstSampleAp  
  8. {  
  9.    public class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.   
  14.             MyContext context = new MyContext();  
  15.             Employee emp = new Employee() { EmpID = 1, EmpName = "Shiju", Address = "Cochin" };  
  16.             context.Employees.Add(emp);  
  17.             context.SaveChanges();  
  18.               
  19.         }  
  20.     }  
  21. }  
Yes! Our Code First application is completed.
 
Go to our db. It automatically created the new db name CompanyDB that we specified in the AppConfig file.
 
 
Check whether the table has our inserted value.
 
 

Conclusion

 
In this article, we learned the basic details of the Code First approach of the Entity Framework.