How do I use MigratorScriptingDecorator in Entity Framework code first?
-
13-12-2019 - |
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?
Solution
As noted on the linked Microsoft Connect issue the problem was a reuse of the same DbMigrator
on several MigratorScriptingDecorator
s.
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("-------------------------------------");
}