Automated Database Migration in Entity Framework Code-First

Automated Database Migration in Entity Framework Code-First Approach

In this article, I am going to discuss Automated Database Migration in Entity Framework Code-First Approach with Examples. Please read our previous article where we discussed How to Seed Data into Database Tables in Entity Framework Code-First Approach.

Database Migration in Entity Framework Code-First Approach

Entity Framework Code-First Supports different database initialization strategies such as CreateDatabaseIfNotExists, DropCreateDatabaseIfModelChanges, and DropCreateDatabaseAlways. As we already discussed, there are certain problems with these database initialization strategies. For example, if we already have data (other than seed data) or existing Stored Procedures, Functions, Triggers, etc. in our database, then these database initialization strategies will drop the entire database and recreate it. As a result, we would lose the data and other Database objects.

The Entity Framework provides a migration tool that automatically updates the database schema when our model changes without losing any existing data or other database objects such as Stored Procedures, Triggers, Functions, etc. It uses a new database initializer called MigrateDatabaseToLatestVersion. There are two kinds of Migration:

  1. Automated Database Migration
  2. Code-Based Database Migration
Example to understand Database Migration using Entity Framework:

Let us understand how to implement database migration in Entity Framework Code First Approach with Examples. Please create the following Student and Standard Entities.

Student.cs

Create a class file with the name Student.cs and then copy and paste the following code into it.

namespace EFCodeFirstDemo
{
    public class Student
    {
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int StandardId { get; set; }
        public Standard Standard { get; set; }
    }
} 
Standard.cs

Create a class file with the name Standard.cs and then copy and paste the following code into it.

using System.Collections.Generic;
namespace EFCodeFirstDemo
{
    public class Standard
    {
        public int StandardId { get; set; }
        public string StandardName { get; set; }
        public string Description { get; set; }
        public ICollection<Student> Students { get; set; }
    }
}

Please make sure to have the connection string with the name MyConnectionString within the app.config file or web.config file as shown in the below image.

Automated Database Migration in Entity Framework Code-First Approach

Automated Database Migration in Entity Framework Code First Approach

The Entity Framework introduced automated migration which will process the database migration automatically. That means we do not have to process database migration manually for each change that we made in our domain classes.

The Automated Migrations can be implemented in Entity Framework by executing the enable-migrations command in the Package Manager Console. To do so, open the Package Manager Console from Tools → NuGet Package Manager → Package Manager Console as shown in the below image.

Automated Database Migration in Entity Framework Code First Approach

Once you open the Package Manager Console, then run the enable-migrations –EnableAutomaticMigration:$true command (make sure that the default project is the project where your context class is located) and press the enter button as shown in the below image.

enable-migrations –EnableAutomaticMigration:$true

Once the above command is executed successfully in the Package Manager Console, it creates an internal sealed Configuration class which is derived from DbMigrationConfiguration class in the Migration folder in our project as shown in the below image.

Example to understand Database Migration using Entity Framework

Now, open the Configuration sealed class and you will the following. As you can see in the constructor of the Configuration class, AutomaticMigrationsEnabled is set to true. Here, additionally, we have added the AutomaticMigrationDataLossAllowed property value to True.

namespace EFCodeFirstDemo.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<EFCodeFirstDemo.EFCodeFirstContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
            ContextKey = "EFCodeFirstDemo.EFCodeFirstContext";
        }

        protected override void Seed(EFCodeFirstDemo.EFCodeFirstContext context)
        {
        }
    }
}

The next step is to set the database initializer in the context class to MigrateDatabaseToLatestVersion. To do so, please modify the context class as follows.

using System.Data.Entity;
namespace EFCodeFirstDemo
{
    public class EFCodeFirstContext : DbContext
    {
        public EFCodeFirstContext() : base("name=MyConnectionString")
        {
            //Setting the Database Initializer as MigrateDatabaseToLatestVersion
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<EFCodeFirstContext, EFCodeFirstDemo.Migrations.Configuration>());
        }
        
        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
    }
}

We are done with the required setting for Automated Migration in Entity Framework Code First Approach. Entity Framework will automatically take care of the migration when we change the domain classes. Next, modify the Main method of the Program class as follows. Here, we are simply adding two standards and two students entity into the Standards and Students database table.

using System;
namespace EFCodeFirstDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EFCodeFirstContext context = new EFCodeFirstContext())
            {
                //Adding Standards
                var standard1 = new Standard() {StandardId = 1, StandardName = "Standard-1", Description = "Standard-One"};
                var standard2 = new Standard() {StandardId = 2, StandardName = "Standard-2", Description = "Standard-Two" };
                context.Standards.Add(standard1);
                context.Standards.Add(standard2);
                context.SaveChanges();
                Console.WriteLine("Standards Added");

                //Adding Standards
                var student1 = new Student() { FirstName = "Pranaya", LastName = "Rout", StandardId = 1 };
                context.Students.Add(student1);
                var student2 = new Student() { FirstName = "Anurag", LastName = "Mohanty", StandardId = 2 };
                context.Students.Add(student2);

                context.SaveChanges();
                Console.WriteLine("Students Added");
            }
            Console.ReadKey();
        }
    }
}

With the above changes in place, now run the application and look at the created database tables and you should see the following.

Automated Database Migration in Entity Framework Code-First Approach with Examples

Here, you can see, the Entity Framework API created a system table called __MigrationHistory along with the Students and Standards tables. If you verify the database tables, then you will see the following data.

Automated Database Migration in Entity Framework Code-First Approach with Examples

The __MigrationHistory table contains the history of database changes for all the migrations. Now, you can add new domain classes, and when you run the application again and you will see that the database contains tables for all entities automatically. You do not need to run any command explicitly. Let us add the following Course Entity.

namespace EFCodeFirstDemo
{
    public class Course
    {
        public int CourseId { get; set; }
        public string CourseName { get; set; }
        public string Description { get; set; }
    }
}

Next, modify the context class as follows:

using System.Data.Entity;
namespace EFCodeFirstDemo
{
    public class EFCodeFirstContext : DbContext
    {
        public EFCodeFirstContext() : base("name=MyConnectionString")
        {
            //Setting the Database Initializer as MigrateDatabaseToLatestVersion
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<EFCodeFirstContext, EFCodeFirstDemo.Migrations.Configuration>());
        }
        
        public DbSet<Student> Students { get; set; }
        public DbSet<Standard> Standards { get; set; }
        public DbSet<Course> Courses { get; set; }
    }
}

Next, add one Stored Procedure in the database. Please execute the following script to create a stored procedure in the database.

-- Student_Insert Stored Procedure
CREATE PROCEDURE [dbo].[Student_Insert]
    @FirstName [nvarchar](max),
    @LastName [nvarchar](max),
 @StandardId INT
AS
BEGIN
    INSERT [dbo].[Students]([FirstName], [LastName], [StandardId])
    VALUES (@FirstName, @LastName, @StandardId)
END
GO

Next, modify the Main Method of the Program class as follows.

using System;
namespace EFCodeFirstDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EFCodeFirstContext context = new EFCodeFirstContext())
            {
                //Adding Standards
                var course = new Course() {CourseName = "C#", Description = "C#.NET"};
                context.Courses.Add(course);
                context.SaveChanges();
                Console.WriteLine("Standards Added");
            }
            Console.ReadKey();
        }
    }
}

With the above changes in place, run the application and verify the database. You will see the newly created Courses table as well as you will see that the Stored Procedure which we created is also there.

Migration in Entity Framework Code-First Approach

Now, if you verify the data, then you will also see that the old Standard and Student data are kept in the database as expected as shown in the below image along with the course table data.

Migration in Entity Framework Code-First Approach

Now, let us modify the existing entity. So, what we are going to do is, we are going to remove the LastName property of the Student Entity as well as we are adding a new property called Branch within the Student Entity. So, modify the Student Entity as follows.

namespace EFCodeFirstDemo
{
    public class Student
    {
        public int StudentId { get; set; }
        public string FirstName { get; set; }
        public string Branch { get; set; }
        public int StandardId { get; set; }
        public Standard Standard { get; set; }
    }
}

Next, modify the Main method of the Program class as follows. Here, we are adding two new students.

using System;
namespace EFCodeFirstDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (EFCodeFirstContext context = new EFCodeFirstContext())
            {
                //Adding Standards
                var student1 = new Student() { FirstName = "Priyanka", Branch = "CSE", StandardId = 1 };
                context.Students.Add(student1);
                var student2 = new Student() { FirstName = "Hina", Branch = "CSE", StandardId = 2 };
                context.Students.Add(student2);

                context.SaveChanges();
                Console.WriteLine("Students Added");
            }
            Console.ReadKey();
        }
    }
}

With the above changes in place, now run the application and then verify the Students database table and its data in the database. Here, you will see that the LastName property is removed and the Branch property is added as shown in the below image.

Migration in Entity Framework

As you can see, for the Existing record it will take NULL values for the Branch column as the Branch column is a Nullable column. If you create an integer column, the existing record will store 0.

In the next article, I am going to discuss Code Based Database Migration in Entity Framework Code-First Approach with Examples. Here, in this article, I try to explain Automated Database Migration in Entity Framework Code-First with Examples. I hope you enjoy this Automated Database Migration in Entity Framework Code-First article. Please give your valuable feedback and suggestions about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *