EF Code-Based Migrations

Sharing schema changes to a database is a big challenge when working on an application. In the past, people would write SQL change scripts, check them into the code, and then have to tell everyone which scripts they need to run. It also required a lot of bookkeeping to know which of these scripts had to be run against the production database when the next version of the application was deployed.

EF Code-Based Migrations is a code-driven, structured way of making changes to the database and is included in Entity Framework 4.3 and above.

Although I won't cover all the details of Migrations here, I will cover some of the ways we make use of migrations. Expand the Migrations folder to see the list of migrations included in the NuGet Gallery, as shown in Figure 16.8. The migrations are named with a timestamp prefix to ensure they run in order.

The one named 201110060711357_Initial.cs is the starting point. This file creates the initial set of tables. After that, each migration applies schema changes as we develop the site and make changes.

Use the NuGet Package Manager Console to create migrations. For example, suppose I add a property named Age to the User class. I can open up the Package Manager Console and run the following command:

Add-Migration AddAgeToUser

Add-Migration is the command to add a new migration, and AddAgeToUser is the name of the migration. I try to pick something descriptive so that I remember what the migration does. It generated a file named 201204292258426_AddAgeToUser.cs, with the migration code shown in Listing 16-3.

Listing 16.3 : Listing 16-3: 201204292258426_AddAgeToUser.cs Migration

namespace NuGetGallery.Migrations
{
    using System.Data.Entity.Migrations;
    public partial class AddAgeToUser : DbMigration
    {

        public override void Up()
        {
            AddColumn("Users", "Age", c => c.Int(nullable: false));
        }

        public override void Down()
        {
            DropColumn("Users", "Age");
        }
    }
}

Very cool! It was able to detect changes to my entities and create the appropriate migration for me. Now I'm free to edit that migration if I need to customize it, but for the most part, I didn't have to keep track of every little change as I developed. Of course, there are changes that it can't automatically create a migration for. If you have a property Name and decide to split it into two properties, FirstName and LastName, you'll need to write some custom migration code for that. But for simple changes, this works wonderfully.

As you develop the code, someone else might add a few migrations to the code. Typically, you'll run the Update-Database command to run all migrations that have not been applied to your local database. Likewise, when you deploy the application, you'll need to run the corresponding migrations against the production site.

The NuGet Gallery codebase runs migrations automatically every time you run the site. Once again, we turn to AppActivator.cs to see how this is configured. The DbMigratorPostStart method has the following two lines that do the magic:

var dbMigrator = new DbMigrator(new MigrationsConfiguration());
dbMigrator.Update();

MigrationsConfiguration is a class that derives from DbMigrationsConfiguration and contains custom configuration for Code First Migrations. Override the Seed method to create initial seed data which will be run after migrations are run. Make sure that the method checks for the existence of the data before it tries to create it again. The NuGet Gallery, for example, overrides this method and adds the “Admins” role, if it doesn't already exist. In the constructor, we disabled automatic migrations:

public MigrationsConfiguration()
{
    AutomaticMigrationsEnabled = false;
}

This is a personal preference, as most of us prefer to be explicit about migrations. When enabled, Code First Migrations can automatically perform migrations to ensure the database matches the current state of the code. So, in the example where I added the Age property to the User class, I wouldn't need to run the Add-Migration command. I simply run the Update-Database PowerShell command and Code First handles it automatically. Since it's not possible to ensure that every change can be made automatically, Code First can mix explicit and automatic migrations. It's a bit too much magic for my tastes, but definitely try it yourself.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset