Running & Scripting Migrations From Code

05/09/2012 23:16:00 By Felipe Pessoto

Rowan Miller explained how to script Migrations from code, but his code was write using a pre-RTM version of Code First Migrations and doesn´t work when using EntityFramework 4.3.1.

I did some reflector work and get a solution that should work.

The most obvious difference is that some classes was renamed. Another point, at least in my case I needed to configure some additional things, like MigrationsAssembly
and MigrationsNamespace, these properties are used to find Code-Based migrations, that is what I want instead of use Automatic Migrations.

The code that does the magic:

System.Data.Entity.Migrations.DbMigrationsConfiguration configuration =newSystem.Data.Entity.Migrations.DbMigrationsConfiguration();
configuration.ContextType=typeof(FujiyBlogDatabase);//TODO Change to your DbContext
configuration.MigrationsAssembly= configuration.ContextType.Assembly;
configuration.MigrationsNamespace="FujiyBlog.Core.Migrations";//TODO Namespace that contains your migrations classes

var migrator =new System.Data.Entity.Migrations.DbMigrator(configuration);

if(true)//TODO Do you want the script or Update de database?
{
    var scriptor =newSystem.Data.Entity.Migrations.Infrastructure.MigratorScriptingDecorator(migrator);
    string script = scriptor.ScriptUpdate(sourceMigration:null, targetMigration:null);
}
else
{
    migrator.Update();
}

Comments (0)