显示来自代码的挂起自动迁移

Display Pending Automatic Migrations from Code

背景

我们在一个地理分布的团队中工作。每隔一段时间,世界另一端的团队会为集成服务器创建构建,但由于

而失败

Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.

我们使用基于代码的迁移。

为了简化故障排除,我正在寻找一种方法来显示从代码中应用了哪些自动迁移,如果允许自动迁移。用于编写新迁移脚本的环境在出现问题的集成服务器上不存在。

尝试的解决方案

我尝试使用 DbMigrator as outlined here,但它似乎只显示尚未应用的基于代码的迁移。

问题

是否有基于代码的方法来显示将应用的更改,是否启用了自动迁移?

这是一个对我有用的解决方案

public string GetAutomaticMigrationsScript<T>() where T : DbMigrationsConfiguration, new()
{
    var configuration = new T();
    configuration.AutomaticMigrationDataLossAllowed = true;
    configuration.AutomaticMigrationsEnabled = true;
    var migrator = new DbMigrator(configuration);
    var scriptor = new MigratorScriptingDecorator(migrator);
    var script = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: null);

    return script;
}

用法:

Console.WriteLine(GetAutomaticMigrationsScript<MyConfiguration>());

变量 script 将包含 SQL 脚本,该脚本将 运行 执行自动迁移。此代码不会实际执行迁移,但您可以将 script 的内容粘贴到 SSMS 中,然后将 运行 迁移到那里。