Question

I have problems using the MigratorScriptingDecorator.ScriptUpdate in Entity Framework 4.3.1.

When specifying sourceMigration and targetMigration only my initial migration gets written, the rest of my migrations become empty.

I have entered a bug report on Microsoft Connect containing reproducing code. https://connect.microsoft.com/VisualStudio/feedback/details/731111/migratorscriptingdecorator-in-entity-framework-migrations-does-not-respect-sourcemigration-and-targetmigration

I expect MigratorScriptingDecorator.ScriptUpdate("from", "to") to behave exactly like the corresponding PM command

PM> Update-Database -Script -SourceMigration from -TargetMigration to

Should ScriptUpdate be equivalent to Update-Database -Script?
Are there any other ways of generating update scripts from code?

Was it helpful?

Solution

As noted on the linked Microsoft Connect issue the problem was a reuse of the same DbMigrator on several MigratorScriptingDecorators.

The original code was

DbMigrator efMigrator = new DbMigrator(new Configuration());
var pendingMigrations = efMigrator.GetLocalMigrations().ToList();
pendingMigrations.Insert(0, "0");
foreach (var migration in pendingMigrations.Zip(pendingMigrations.Skip(1), Tuple.Create))
{
    var sql = new MigratorScriptingDecorator(efMigrator).ScriptUpdate(migration.Item1, migration.Item2); // <-- problem here, the efMigrator is reused several times
    Console.WriteLine("Migration from " + (migration.Item1 ?? "<null> ") + " to " + (migration.Item2 ?? "<null> "));
    Console.WriteLine(sql);
    Console.WriteLine("-------------------------------------");
}

the MigratorScriptingDecorator should be instantiated outside the loop like this:

DbMigrator efMigrator = new DbMigrator(new Configuration());
var pendingMigrations = efMigrator.GetLocalMigrations().ToList();
pendingMigrations.Insert(0, "0");
var scriptMigrator = new MigratorScriptingDecorator(efMigrator); // <-- now only one MigratorScriptingDecorator is created for the DbMigrator
foreach (var migration in pendingMigrations.Zip(pendingMigrations.Skip(1), Tuple.Create))
{
    var sql = scriptMigrator.ScriptUpdate(migration.Item1, migration.Item2);
    Console.WriteLine("Migration from " + (migration.Item1 ?? "<null> ") + " to " + (migration.Item2 ?? "<null> "));
    Console.WriteLine(sql);
    Console.WriteLine("-------------------------------------");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top