Code First Development Approach With Entity Framework

Which one to use in your project is completely your choice and also what you already have in place. Meaning are you designing/developing something from scratch or you already have got DB or domain classes, and also what are your preferences, meaning do you prefer to design classes first and then let your DB gets developed from those classes or you like to design visual class diagram first.

Entity framework provides you three main approaches when working with the database and data access layer in your application.

  1. Code First
    • With completely new DB
    • With existing DB
  1. Database First
  2. Model First

Which one to use in your project is completely your choice and also what you already have in place. Meaning are you designing/developing something from scratch or you already have got DB or domain classes, and also what are your preferences, meaning do you prefer to design classes first and then let your DB get developed from those classes or do you like to design visual class diagram first.

Below diagram can help you in this,

Entity Framework

Code first and DB first are two very popular approaches.

By using code first, you have full control on your database. Your code defines the database and you can do better version control of the database. At the time of initial creation you can have a file which will be the baseline of dthe atabase and going forward, whatever incremental changes you will apply to your model ,you can create a separate file. Among all available options, code first database migration is the most powerful feature and whenever you make changes in the model EF will keep track of your changes. (I will explain this with an example later in this article).

DB First is equally popular and mostly used if you have DB designed and developed by DBAs or DB designer or if you have an already existing DB. In this, you will let entity framework create entities for you in the form of Plain Old CLR Object (POCO). Remember, if you want additional changes in these POCO, you need to develop partial classes on your own. You cannot modify the classes which got created by EF.

Out of the three in my honest opinion, Model first is the least used and will only be used if you are a hard core designer and love design and do not like code or SQL. You will draw your model and workflow will generate your database script.

Entity Framework (Code first)
Entity Framework
I have created a simple console application to explain that how entity framework works with code first.

  1. Created a console application and in that application, I have installed Nuget package.

    (Project ->Manage NuGet package -> Select Entity Framework and install.
  1. Once Entity Framework is installed, you can use the built-in class DbContext.

    (Entity framework provide DbContext class to establish connection to database and query the db. Extending DbContext allows to define database model with DbSet.)
  1. As shown below, LibraryContext is getting derived from DbContext class.

  2. In the LibraryContext class , I have used to two DBSet with two different classes. These two classes used with DbSet , Books and Authors represents the tables in database. Meaning these two are the model classes and in DB these will be defined as tables.

    Entity Framework

  3. Define the connection string in config file,

    Entity Framework

  1. Open the package manager console. (Tools -> Library package console).

  2. Use Enable-Migration command as mentioned below.

    Entity Framework

  3. After the Enable-Migration is completed, we will see a folder with the name “Migrations." Inside that folder you will see a file Configuration.cs.

    Entity Framework

  4. The structure of configuration.cs file is as below. It has the constructor of the class and it also has a method Seed (). Seed() method is generally used to set the master values in the DB.

    Entity Framework

  5. The next step is to run Add-Migration command from package manager. As it is mentioned in the yellow highlighted text below, when we run Add-Migration command, it will create a .cs file with datetime stamp. This file contains two methods Up() and Down(). You can consider, Up() as the deployment script and Down() as rollback scripts.

    Entity Framework
  1. Last and final step is to run the Update-Database command in package manager console.

    Entity Framework

    When you run the Update-Database, it does two steps,
    1. First it runs the Up() method from data time stamp file.
    2. Second it runs Seed() method from configuration file.

      Entity Framework

Let’s do the second migration now,

  1. I have added one new column (highlighted one) in the existing class.
    1. public class Books {  
    2.     [Key]  
    3.     public int Book_ID {  
    4.         get;  
    5.         set;  
    6.     }  
    7.     public string Book_Title {  
    8.         get;  
    9.         set;  
    10.     }  
    11.     public int Author_ID {  
    12.         get;  
    13.         set;  
    14.     }  
    15.     public DateTime Release_Date {  
    16.         get;  
    17.         set;  
    18.     }  
    19. }  
  1. Execute Add-Migration command in package manager console.

  2. It will create a class with the same name specified in your command. This will have Up() method , which contains only the newly updated data. I have edited that method to have default value.

    Entity Framework

    Entity Framework

  1. Finally execute the Update-Database method. Please note that it will only execute newly created file/changes.

    Entity Framework

Conclusion

As explained the above code first approach is the widely accepted and used approach. It helps the developer control the database design and also lets them keep track of the changes. It also maintains version control of the database. In my next blog, I will explain DB first and how to use it with EF in detail.

  • LikeCode First - Development approach with Entity Framework:
  • Comment