问题
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