如何使用TransactionScope在Entity Framework中创建嵌套事务? [英] How to create nested transactions in Entity Framework using TransactionScope?

查看:355
本文介绍了如何使用TransactionScope在Entity Framework中创建嵌套事务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道EF 6 DbContextTransaction,但是我在嵌套事务中遇到了糟糕的经历。

I know EF 6 DbContextTransaction, but I'm getting bad experience with it over nested transaction.

现在我正在尝试使用TransactionScope进行嵌套事务,但是也有问题。

Now I'm trying solely using TransactionScope for nested transaction, but also having problem.

此代码涉及3个表更改。

This code involved 3 tables changes.

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

When an exception occured in inner trx dbTrx2, it messed up dbTrx1, as dataChg3.SaveChanges() will failed.

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();
}



< b $ b

Does anyone ever workout proper nested transaction using entity framework?

推荐答案

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

As at present, EF6 can't properly handle nested transaction.

我的解决方法,主要解决我的需要:
- 当嵌套事务发生异常时,坏的数据更改不会影响/携带到下一个SaveChanges()调用。

My workaround, primary to address my need: - when exception occurred in nested transaction, bad data changes will not affect/bring-fort to next SaveChanges() invoke.

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

这篇关于如何使用TransactionScope在Entity Framework中创建嵌套事务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆