【问题标题】:Proper TransactionScope for nested transactions嵌套事务的正确 TransactionScope
【发布时间】:2014-10-13 11:54:25
【问题描述】:

我想将第一个事务范围设置为任何东西(一般的东西),并始终在第二个事务范围中设置隔离级别。这可能吗?

    using (var scope = new TransactionScope())
    {
        using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead }))
        {
                // some service logic
        }
    }

第二个 using 语句引发错误:为 TransactionScope 指定的事务的 IsolationLevel 与为范围请求的值不同

当前错误是第一个 transactionScope 默认为 Serializable,我无法添加新数据,但在 repeatableRead 中我可以添加数据。

【问题讨论】:

    标签: asp.net transactionscope


    【解决方案1】:

    你可以使用这样的东西

    var option1 = new TransactionOptions
    {
     IsolationLevel = IsolationLevel.ReadCommitted,
     Timeout = TimeSpan.FromSeconds(60)
    };
    
    var option2 = new TransactionOptions
    {
     IsolationLevel = IsolationLevel.RepeatableRead,
     Timeout = TimeSpan.FromSeconds(60)
    };
    
    using (var scopeOuter = new TransactionScope(TransactionScopeOption.Required, option1))
    {
    using (var conn = new SqlConnection(connectionString))
    {
        using (SqlCommand cmd = conn.CreateCommand())
        {
    
        }
    }
    using (var scopeInner = new TransactionScope(TransactionScopeOption.Required, option2))
    {
        using (var conn = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = conn.CreateCommand())
            {
    
            }
        }
        scopeInner.Complete();
    }
    scopeOuter.Complete();
    

    }

    希望对你有帮助..

    【讨论】:

    • 是的,我已经做过类似的事情。这是一个很好的方法。
    • 我很困惑,为什么这个被接受的答案 - 我完全按原样尝试了代码,正如预期的那样,它导致 System.ArgumentException :为 TransactionScope 指定的事务具有与值不同的 IsolationLevel要求的范围。参数名称:transactionOptions.IsolationLevel
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 2015-06-24
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    相关资源
    最近更新 更多