【问题标题】:Can Entity Framework 6 migrations include a transaction around scripts?Entity Framework 6 迁移是否可以包含围绕脚本的事务?
【发布时间】:2015-11-07 22:46:50
【问题描述】:

非常简单的问题,我在实体框架 6 中使用迁移,并且喜欢命令

update-database -script

但是有没有一种方法可以生成脚本但将其与事务包装在一起?

问题是如果脚本失败,我必须取消它

【问题讨论】:

标签: c# .net entity-framework entity-framework-6


【解决方案1】:

这是我仅在发布模式下用来生成脚本的:

public class MigrationScriptBuilder : SqlServerMigrationSqlGenerator
{
#if !DEBUG
    protected override void Generate(SqlOperation sqlOperation)
    {
        Statement("GO");

        base.Generate(sqlOperation);

        Statement("GO");
    }

    public override IEnumerable<MigrationStatement> Generate(IEnumerable<MigrationOperation> migrationOperations, string providerManifestToken)
    {
        yield return new MigrationStatement {Sql = "BEGIN TRAN"};

        foreach (var migrationStatement in base.Generate(migrationOperations, providerManifestToken))
        {
            yield return migrationStatement;
        }

        yield return new MigrationStatement {Sql = "COMMIT TRAN"};
    }
#endif
}

你应该把它连接到你的DatabaseMigrationsConfiguration。示例:

public sealed class DatabaseMigrationsConfiguration : DbMigrationsConfiguration<DatabaseContext>
{
    public DatabaseMigrationsConfiguration()
    {
        SetSqlGenerator("System.Data.SqlClient", new MigrationScriptBuilder());
    }
}

【讨论】:

  • 你是如何使用这个的?我把这个放在哪里?你能运行update-database -script 并生成包含事务的脚本吗?
  • 对不起,我已经添加了哪里。
  • 请注意,此答案不处理 SuppressTransactiontrue 的语句,但它们很少见,因此在实践中可能无关紧要。
  • 你有什么理由只为了发布而不是为了调试?
  • 在没有 -script 的 Visual Studio 控制台中不起作用
猜你喜欢
  • 2022-01-07
  • 1970-01-01
  • 2022-11-17
  • 1970-01-01
  • 2019-01-11
  • 2019-09-02
  • 1970-01-01
  • 2014-02-07
  • 2017-10-12
相关资源
最近更新 更多