Wie verwende ich MigratorScriptingDecorator zuerst im Entity Framework-Code?
-
13-12-2019 - |
Frage
Ich habe Probleme mit dem MigratorScriptingDecorator.ScriptUpdate
im Entity Framework 4.3.1.
Wenn Sie sourceMigration und targetMigration angeben, wird nur meine anfängliche Migration geschrieben, der Rest meiner Migrationen wird leer.
Ich habe einen Fehlerbericht zu Microsoft Connect eingegeben, der Reproduktionscode enthält.https://connect.microsoft.com/VisualStudio/feedback/details/731111/migratorscriptingdecorator-in-entity-framework-migrations-does-not-respect-sourcemigration-and-targetmigration
Ich erwarte MigratorScriptingDecorator.ScriptUpdate("from", "to")
so verhalten Sie sich genau wie der entsprechende PM-Befehl
PM> Update-Database -Script -SourceMigration from -TargetMigration to
Sollte ScriptUpdate äquivalent sein zu Update-Database -Script
?
Gibt es andere Möglichkeiten, Aktualisierungsskripte aus Code zu generieren?
Lösung
Wie im verknüpften Microsoft Connect-Problem erwähnt, war das Problem eine Wiederverwendung desselben DbMigrator
auf mehreren MigratorScriptingDecorator
s.
Der ursprüngliche Code war
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("-------------------------------------");
}
der MigratorScriptingDecorator
sollte außerhalb der Schleife wie folgt instanziiert werden:
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("-------------------------------------");
}