【问题标题】:How to create nested transactions in Entity Framework using TransactionScope?如何使用 TransactionScope 在实体框架中创建嵌套事务?
【发布时间】:2015-11-16 03:37:52
【问题描述】:

我知道 EF 6 DbContextTransaction,但我对嵌套事务的体验很糟糕。

现在我正在尝试仅将 TransactionScope 用于嵌套事务,但也遇到了问题。

此代码涉及 3 个表更改。

当内部 trx dbTrx2 发生异常时,它搞砸了 dbTrx1,因为 dataChg3.SaveChanges() 将失败。

using (var dbTrx1 = new System.Transactions.TransactionScope())
{
    ...
    dataChg1.....

    foreach(var dataChg2 in listOfDataChg2)
    {
        ...
        try
        {
            using (var dbTrx2 = new System.Transactions.TransactionScope())
            {
                ...
                dbTrx2.Complete();
            }
        }
        catch(Exception ex)
        {
            ...
            // when ex occured in dbTrx2, it messed up dbTrx1
        }
        ...
    }

    dataChg3.SaveChanges(); // <- error - The operation is not valid for the state of the transaction
    ...
    dbTrx1.Complete();
}

有人曾经使用实体框架锻炼过正确的嵌套事务吗?

【问题讨论】:

    标签: entity-framework-6 transactionscope


    【解决方案1】:

    目前,EF6 无法正确处理嵌套事务。

    我的解决方法,主要是为了满足我的需求: - 当嵌套事务中发生异常时,错误的数据更改不会影响/带来下一次 SaveChanges() 调用。

    https://social.microsoft.com/Forums/en-US/4d359652-d3ff-4127-bb94-c7bd40ba58c7/entity-framework-6-partially-using-transactionscope?forum=adodotnetentityframework

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      相关资源
      最近更新 更多