适用于嵌套事务的TransactionScope

时间:2014-10-13 11:54:25

标签: asp.net transactionscope

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

    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中我可以添加数据。

1 个答案:

答案 0 :(得分: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();

}

我希望它有所帮助..