Code First Entity Framework


In the Code First approach, the focus can be on the domain design and creating classes as in the domain requirements rather than designing the database first and then creating the classes that match the database design. Code First APIs create the database on the fly based on the entity classes and configuration.


So, being a developer I guess the Code First approach would be a fine approach rather than focusing on creating databases.

Using the code

  1. namespace SchoolDataLayer  
  2. {       
  3.     public class Context: DbContext   
  4.     {  
  5.         public Context(): base()  
  6.         {              
  7.         }  
  8.         public DbSet<Student> Students { getset; }  
  9.         public DbSet<Standard> Standards { getset; }  
  10.     }  

First create classes as required for the Domain (Domain Driven Design).

  1. public class Student  
  2. {  
  3.     public Student()  
  4.     {   
  6.     }  
  7.     public int StudentID { getset; }  
  8.     public string StudentName { getset; }  

Create a Context Class derived from the DbContext class present in the using System.Entity namespace.

In the DbContext class we add the DbSet<T> of the classes.

And then creating a Console Application with the following code as (just a snippet for reference):

  1. using (var ctx = new Context())  
  2. {  
  3.     Student stud = new Student() { StudentName = &quot;New Student&quot; };  
  5.     ctx.Students.Add(stud);  
  7.     ctx.SaveChanges();                  

Points of Interest

  • Code First first checks if the Connection String is ed in the DbContext base constructor.

  • If the database is present in the connection string then it uses the database else creates a new one.

  • If a connection string is also not present, then the database name is ed in the context base constructor.

  • If ed then create the database with the same name.

  • If not then the database is created with the name that matches the Name that matches the Context.

  • Then the parameters are ed in the base constructor (maybe parameterized/parameterless).

In the console application use Entity Framework Reverse Engineering to generate the DbContext classes for the domain classes created.

And in the MVC application we use Migrations in the Package Manager Console. (Enable-Migrations/Update-Database Verbose).

Invincix Solutions Private limited
Every INVINCIAN will keep their feet grounded, to ensure, your head is in the cloud