Manually call DbMigration.Up in EF
c#, entity-framework
Solution
For complete manual control over migrations, you can use the following extension method:
public static void RunMigration(this DbContext context, DbMigration migration)
{
var prop = migration.GetType().GetProperty("Operations", BindingFlags.NonPublic | BindingFlags.Instance);
if (prop != null)
{
IEnumerable<MigrationOperation> operations = prop.GetValue(migration) as IEnumerable<MigrationOperation>;
var generator = new SqlServerMigrationSqlGenerator();
var statements = generator.Generate(operations, "2008");
foreach (MigrationStatement item in statements)
context.Database.ExecuteSqlCommand(item.Sql);
}
}
Example: Having a migration like this:
public class CreateIndexOnContactCodeMigration : DbMigration
{
public override void Up()
{
this.CreateIndex("Contacts", "Code");
}
public override void Down()
{
base.Down();
this.DropIndex("Contacts", "Code");
}
}
You could run it against your DbContext:
using (var dbCrm = new CrmDbContext(connectionString))
{
var migration = new CreateIndexOnContactCodeMigration();
migration.Up(); // or migration.Down();
dbCrm.RunMigration(migration);
}
Problem
I want to be able to Up() method of a migration manually. Currently I'm trying to do that but calling that contains CreateTable method does not create the table. I suspect that connection is not properly set. And there are no properties to set it. I also tried DbMigrator but it calls some internal EF migration methods. So does anyone know how to set a connection to be used by DbMigration.Up method? Thanks in advance!