在.net中使用TransactionScopeOption.Suppress时,为什么忽略隔离级别

我正在尝试使用LINQ TO SQL在现有事务中使用未提交的隔离级别读取执行查询.如果我使用该选项来禁止父事务中的此事务,我似乎失去了指定隔离级别的能力.在LINQPad中使用此代码:

void Main()
{
var db = this;
db.ExecuteQuery<string>(@"SET TRANSACTION ISOLATION LEVEL SERIALIZABLE");

using (var trans = new TransactionScope(TransactionScopeOption.Required))
{
    // updates or inserts here

    using (new TransactionScope(TransactionScopeOption.Suppress,
        new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
    {
        db.ExecuteQuery<string>(@"SELECT CASE transaction_isolation_level 
        WHEN 0 THEN 'Unspecified' 
        WHEN 1 THEN 'ReadUncomitted' 
        WHEN 2 THEN 'Readcomitted' 
        WHEN 3 THEN 'Repeatable' 
        WHEN 4 THEN 'Serializable' 
        WHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL 
        FROM sys.dm_exec_sessions 
        where session_id = @@SPID
        ").Dump("Inside the transaction");

    }
    // updates or inserts here
}
}

我得到了SERIALIZABLE的结果.有没有办法在事务中运行查询并更改隔离级别以读取未提交的?

最佳答案
您要使用的是TransactionScopeOption.RequiresNew. Supress选项使您的封闭块在没有环境事务的情况下运行,也无需创建新的封闭块.这就是它的作用.

RequiresNew导致创建新的根事务范围.

请参阅this article中的摘要表,了解不同选项的行为方式.

更多关于抑制:

Suppress is useful when you want to preserve the operations performed
by the code section, and do not want to abort the ambient transaction
if the operations fail. For example, when you want to perform logging
or audit operations, or when you want to publish events to subscribers
regardless of whether your ambient transaction commits or aborts.

转载注明原文:在.net中使用TransactionScopeOption.Suppress时,为什么忽略隔离级别 - 代码日志