gpt4 book ai didi

entity-framework-6 - 如何使用 TransactionScope 在 Entity Framework 中创建嵌套事务?

转载 作者:行者123 更新时间:2023-12-04 07:54:54 27 4
gpt4 key购买 nike

我知道 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 锻炼过正确的嵌套事务?

最佳答案

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

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

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

关于entity-framework-6 - 如何使用 TransactionScope 在 Entity Framework 中创建嵌套事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33728142/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com