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();
}

FujiyBlog vNext - Automatic Migrations

05/09/2012 23:05:24 By Felipe Pessoto

Com o suporte ao unicode aproveitei pra testar a criação das migrations e scripts SQL. Há algum tempo tentei automatizar o processo, seguindo o post do Rowan Miller, PM de ADO.NET Entity Framework, Running & Scripting Migrations From Code, mas não funciona pelo menos na versão 4.3.1. Cheguei a comentar no post mas não tive resposta.

O jeito foi tentar entender o código que faz o Migration, usando o decompiler do Resharper. Consegui chegar num resultado que permite a migração totalmente automática, quando se tem as permissões necessárias no banco de dados, ou a geração do Script dinamicamente. Pretendo criar um post explicando o processo, que é bem simples, e (tentar) fazer uma versão em inglês pois vi que tem várias pessoas com o mesmo problema que tive.