给出以下代码结构
func1()
{
using (TransactionScope1)
using (connection1)
{
"insert into table A"
func2()
"select from table B"
}
}
func2()
{
using (TransactionScope2)
using (connection2)
{
foreach (x in y)
{
"select from table A"
"insert into table B"
}
}
}
如果 TransactionScope2
已回滚,则“从表 B 中选择”
会失败,并显示 操作对于事务状态无效
。据我了解,TransactionScope2 正在与第一个连接并将它们都回滚。
因此,我将其更改为使用 TransactionScopeOption.RequiresNew
创建它,这又导致 “从表 A 中选择”
超时。
这个想法是让第二个事务从第一个事务读取数据,但独立提交/回滚。我的猜测是 IsolationLevel
需要以某种方式进行更改,但我不太了解它的选项。
编辑:
如果我们将 func1
和 2 命名,也许更容易理解问题。基本上,func2
是一个 DAL 功能,而 func1
是一个单元测试一下。 func1
创建一些示例数据,获取 func2
对其执行一些操作,检查结果,然后回滚整个数据,无论 func2
位于何处成功与否。
编辑2:阅读更多内容后,我认为以下代码应该可以工作,但由于某种原因,我仍然在从表A中选择
func1()
{
using (var txn = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }))
using (connection1)
{
"insert into table A"
func2()
"select from table B"
}
}
func2()
{
using (var txn = new TransactionScope(TransactionScopeOption.RequiresNew))
using (connection2)
{
foreach (x in y)
{
"select from table A"
"insert into table B"
}
}
}
最佳答案
您有一个nested TransactionScope 。
默认情况下,它们是链接的,无需您采取进一步操作 ( RequiresNew ),当内部作用域失败时,外部作用域将失败(回滚)。
这样他们就会独立:
func2()
{
using (TransactionScope2 =
new TransactionScope(TransactionScopeOption.RequiresNew))
using (connection2)
{
...
}
}
关于c# - 难以理解 TransactionScope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12503089/