Code First Migrations in Entity Framework

Introduction

If you understand Code First Entity Framework then this article is easy to understand the concept of 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 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:
    using System;  
    using System.Collections.Generic;  
    using System.Data.Entity;  
    using System.Linq;  
    using System.Text;  
    using System.Threading.Tasks;  
      
    namespace CodeFirstMigration  
    {  
        public class EmployeeContext : DbContext  
        {  
            public DbSet<Employee> Employees { get; set; }  
        }  
      
        public class Employee  
        {  
            public int EmployeeID { get; set; }  
            public string EmpName { get; set; }  
        }  
    }
  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:
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Text;  
    using System.Threading.Tasks;  
      
    namespace CodeFirstMigration  
    {  
        class Program  
        {  
            static void Main(string[] args)  
            {  
                using (var context = new EmployeeContext())  
                {  
                    //Insert values in database  
                    context.Employees.Add(new Employee { EmployeeID = 1, EmpName = "krishna" });  
                    context.Employees.Add(new Employee { EmployeeID = 2, EmpName = "radha" });  
                    context.SaveChanges();  
      
                    //Get all values from database  
                    foreach (var emp in context.Employees)  
                    {  
                        Console.WriteLine("Employee ID : " + emp.EmployeeID);  
                        Console.WriteLine("Employee Name : " + emp.EmpName);  
                    }  
                }  
      
                Console.WriteLine("Press Any key to exit....");  
                Console.ReadKey();  
            }  
        }  
    }
  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 changes to our model. Add a new property Role to the Employees table.
    public string Role { get; set; } 
  2. Run the application. You will not get the error “InvalidOperationException” like the following:

    main function

  3. Now it's time to use the 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 classes to your project in the Migrations folder.
    • 201411061912454_InitialCreate.cs This migration was generated because Code First already created a database for us before we enabled migrations.
    • 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 class 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, 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.


Similar Articles