Domanda

I'm trying to execute an query with the isolation level read uncommitted within an existing transaction using LINQ TO SQL. If I use the option to suppress this transaction from the parent transaction, it seems I lose the ability to specify the isolation level. Using this code in 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
}
}

I get the result of SERIALIZABLE. Is there any way to run a query inside a transaction and change the isolation level to read uncommitted?

È stato utile?

Soluzione

What you want to use is TransactionScopeOption.RequiresNew. The Supress option causes your enclosing block to run without an ambient transaction and also without creating a new one. That's what it does.

RequiresNew causes a new, root transaction scope to be created.

See the summary table in this article on how different options behave.

More on Suppress:

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top