c# - 难以理解 TransactionScope

标签 c# sql transactions

给出以下代码结构

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/

相关文章:

mysql - 表示具有可变长度类别和子类别的实体

c# - 在 C# 中使用 AWS Cloudfront API 创建签名 Cookie

c# - 如何在 Dot Net Core 3.1 中使用 FromSqlInterpolated/Database.ExecuteSqlInterpolated 执行带有输出参数的存储过程?

c# - 确保泛型集合包含派生自两个基础对象的对象

php - CakePHP 3.x : Query to exclude records in which a field can be either NULL or empty ('' )

python - 具有多对多字段的 Django 条件排序

c# - WPF - 删除带有 Validation.Error 的 DataGridRow block DataGrid

postgresql - 关于Postgres track_commit_timestamp (pg_xact_commit_timestamp)的问题

sql - 您如何在SQLite中进行事务处理?

java - @Transaction - 如何在同一个事务中提交另一个方法