How do I use MigratorScriptingDecorator in Entity Framework code first?

不羁的心 提交于 2019-12-11 04:51:19

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/9701781/how-do-i-use-migratorscriptingdecorator-in-entity-framework-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!