【问题标题】:Does a transaction Rollback() have any chance to throw an exception?事务 Rollback() 是否有机会抛出异常?
【发布时间】:2018-03-17 02:37:02
【问题描述】:

与使用 EF Core 管理事务相关的问题:

IDbContextTransaction.Rollback() 是否有机会返回异常,以便将其放在 try 块中?

    try
    {
        //...
        if(condition)
            transaction.Commit();
        else
            throw methodReturn.Exception;
    }
    catch (Exception e)
    {
        try     // Does this try make any sense?
        {
            transaction.Rollback();
        }
        catch
        {
            // Log
        }
        throw e;
    }

PD:在这种特定情况下,无法将事务嵌入到using 语句中,因此在实际代码中需要手动调用.Rollback()

【问题讨论】:

标签: c# entity-framework asp.net-core transactions entity-framework-core


【解决方案1】:

大多数时候还没有到:

  1. 死锁检测
  2. 没有互联网连接
  3. 逻辑和物理一致的连接
  4. 关机、电源故障、意外终止

要解决这些情况,您可以:

  1. 使用 Xact_Abort 设置。当 SET XACT_ABORT 为 ON 时,如果 Transact-SQL 语句引发运行时错误,则整个事务将终止并回滚。 当 SET XACT_ABORT 为 OFF 时,在某些情况下,只有引发错误的 Transact-SQL 语句被回滚并且事务继续处理。根据错误的严重程度,即使 SET XACT_ABORT 为 OFF,也可能回滚整个事务。关闭是默认设置。

  2. 捕获并处理错误,并在错误处理中指定回滚

【讨论】:

    猜你喜欢
    • 2016-11-16
    • 2017-03-11
    • 1970-01-01
    • 2021-01-10
    • 2015-10-03
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多