Code First Migrations in Entity Framework

Introduction

If you understand Code First Entity Framework then this article is easy to understand the concept Code First Migration in Entity Framework. If you are unfamiliar with Code First then read this article Code First Entity Framework.

Code First Migration

You have created a database as per the domain requirements and you forgot a column that must exist in the table. You check and the column is not present. You then need not to create and delete the existing model to add the new column or table in the database when this approach is used. Code First Migrations allow you to create a new database or update an existing database based on your model classes using the Package Manager Console for running commands.

If you are using the EF code first approach then there are more ways to initialize the database provided by the Entity Framework as follows.

  1. DropCreateDatabaseAlways.

    This database initializer class always drops and creates a new database, whether it is already present or not with every run of the application.

  2. DropCreateDatabaseWhenModelChanges.

    This database initializer class drops the existing database and re-creates it if there is a mismatch between the model classes and table schema.

  3. CreateDatabaseIfNotExists.

This class creates a database only if it doesn't exist. It avoids any accidental deletion of the database.

These three databases to be initialized are provided by EF fail when you are updating the model or classes and then it mismatches when it fails and your database records are lost. Here is one solution for this, EF Code First Migration. Using the approach you can change the model class or table or add new classes. Then no database records are lost and your existing database is also the same.

Creating Model and Database

For using this code first migration you need a database and code first model. Use the procedure for creating the code first model.

  1. Open Microsoft Visual Studio.

  2. "File" -> "New" -> "Project...".

  3. Set the Console Application name as CodeFirstMigration.

  4. Click OK.

  5. Add the EntityFramework NuGet package.

  6. Tools -> Library Package Manager –> Package Manager Console

  7. Run the Install-Package EntityFramework command.

    See the output below:

    package manager console

    See the following red color box that shows the added references for EntityFramework and database:

    entityframework

  8. Add a new class named EmployeeContext.cs to our Entity Framework Code First Context and add the following code.
    Code for EmployeeContext class file:
    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 CodeFirstMigration  
    9. {  
    10.     public class EmployeeContext : DbContext  
    11.     {  
    12.         public DbSet<Employee> Employees { getset; }  
    13.     }  
    14.   
    15.     public class Employee  
    16.     {  
    17.         public int EmployeeID { getset; }  
    18.         public string EmpName { getset; }  
    19.     }  
    20. }  
  9. Now we have a model. It's time to do some operation for data access. Add some code to the Program.cs file as in the following:
    Code for Program class file:
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5. using System.Threading.Tasks;  
    6.   
    7. namespace CodeFirstMigration  
    8. {  
    9.     class Program  
    10.     {  
    11.         static void Main(string[] args)  
    12.         {  
    13.             using (var context = new EmployeeContext())  
    14.             {  
    15.                 //Insert values in database  
    16.                 context.Employees.Add(new Employee { EmployeeID = 1, EmpName = "krishna" });  
    17.                 context.Employees.Add(new Employee { EmployeeID = 2, EmpName = "radha" });  
    18.                 context.SaveChanges();  
    19.   
    20.                 //Get all values from database  
    21.                 foreach (var emp in context.Employees)  
    22.                 {  
    23.                     Console.WriteLine("Employee ID : " + emp.EmployeeID);  
    24.                     Console.WriteLine("Employee Name : " + emp.EmpName);  
    25.                 }  
    26.             }  
    27.   
    28.             Console.WriteLine("Press Any key to exit....");  
    29.             Console.ReadKey();  
    30.         }  
    31.     }  
    32. }  
  10. Save the changes and Run. The output is as in the following:

    output

  11. See in the SQL Server and SQL Server Object Explorer your model CodeFirstMigration.EmployeeContext.

    CodeFirstMigration

    database

Until now we just created the model and added records to the database. The actual concept of Code First Migration is as follows.
  1. Make some more change in our model. Add a new property Role to the Employees table.
    1. public string Role { getset; }  
  2. Run the application. You will not get the error “InvalidOperationException” like the following:

    main function

  3. Now it's time to use Code First Migration approach.

  4. Open Package Manager Console.

  5. Run Enable-Migrations command in a Package Manager console.

    Package Manager Console page

  6. This command added two more class to your project in the Migrations folder.

    1. 201411061912454_InitialCreate.cs

      This migration was generated because Code First already created a database for us, before we enabled migrations.

    2. Configuration.cs

      It allows you to configure how Migrations behave for your context.

      Migrations behaves

  7. Update the database with the new changes we made in the model.

  8. Run Add-Migration MigrationForRoleInEmp in a Package Manager console.

    MigrationForRoleInEmp

    Now it adds one more classes to the Migrations folder in MigrationForRoleInEmp.cs. Let's use Update-Database to apply this migration to the database.

    Migrations folder

  9. Run the Update-Database command in a Package Manager console.

    command in Package manager console

    Code First Migrations will compare the migrations in our Migrations folder with the ones that have been applied to the database. It will see that the MigrationForRoleInEmp migration needs to be applied and run it.

    Finally, the CodeFirstMigration.EmployeeContext database is now updated to include the Role column in the Employees table. See the following image:

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

Summary

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