How to create nested transactions in Entity Framework using TransactionScope?

强颜欢笑 提交于 2019-12-12 13:08:33

问题


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

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

This code involved 3 tables changes.

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

Does anyone ever workout proper nested transaction using entity framework?


回答1:


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

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



来源:https://stackoverflow.com/questions/33728142/how-to-create-nested-transactions-in-entity-framework-using-transactionscope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!