EF迁移migrate.exe生成脚本。

8
我正在尝试使用Entity Framework和持续构建。到目前为止,我能够使用migrate.exe和适当的参数运行迁移或一系列迁移而没有任何问题。
然而,当尝试让migrate.exe生成脚本而不是执行迁移时,我遇到了麻烦,就像我通过运行...
update-database -TargetMigration TestMigration -script

在Visual Studio的软件包管理器控制台中进行操作吗?目前是否有这样的方法?谢谢。
4个回答

7
自从2017年10月22日,您可以通过此PR实现: https://github.com/aspnet/EntityFramework6/commit/02ec6b8c9279f93f80eeed1234e5ce0acfce5f31 这里是实现此功能的Entity Framework 6.2版本发布说明(请参见“Migrate.exe应支持-script选项”部分): https://blogs.msdn.microsoft.com/dotnet/2017/10/26/entity-framework-6-2-runtime-released/ 按照以下步骤操作:
1.将文件migrate.exe从“\packages\EntityFramework.6.2.0\tools”复制到目标“bin”文件夹(例如在生产服务器上),在部署包含新迁移的新程序集后执行此操作。
2.在该文件夹中打开命令行并运行此命令:
migrate.exe yourMigrationAssembly.dll /startupConfigurationFile=”..\web.config” /scriptFile="migrationOutput.sql"
它将生成名为“migrationOutput.sql”的文件,其中包含基于尚未应用于其上的迁移的SQL,您必须在目标环境DB上执行该SQL。

Migrate.exe 还支持新参数 sourceMigration 和 force。 - johey

5

投票已添加。感谢您的回来。 - Greg Smith

3

我遇到了同样的问题,确实在Visual Studio的包管理器控制台中有这个选项。于是我打开了powershell脚本和实体框架dll,并构建了一个小型可执行文件,因此您可以通过命令行生成脚本。源代码可以在此处免费获取,但不提供任何保证:


尝试在回答中加入更多的内容。不要仅仅发布链接,提供一些解释或说明它包含的内容以及如何帮助读者。 - brightintro

3

您可以编写一个简单的C#控制台应用程序,或使用类似于Linqpad的工具来生成通过Entity Framework基础设施对象执行脚本。您只需要加载包含DbMigrationsConfiguration类的DLL,并实例化它即可。以下是与我的代码类似的代码:

using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;

const string ScriptFile = "Migration.sql";
const string ConnectionString = @"Server=.\SqlExpress;Database=...;Trusted_Connection=True;";
const bool AutomaticMigrationDataLossAllowed = false;

var targetDb = new DbConnectionInfo(ConnectionString, "System.Data.SqlClient");
var config = new MyDbMigrationsConfiguration
{
    AutomaticMigrationDataLossAllowed = AutomaticMigrationDataLossAllowed,
    TargetDatabase = targetDb,
};

var migrator = new DbMigrator(config);
var scripter = new MigratorScriptingDecorator(migrator);
var script = scripter.ScriptUpdate(null, null);

File.WriteAllText(ScriptFile, script);
Console.WriteLine("Migration Script Generated: " + ScriptFile);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接