Search code examples
c#sql-server.net-core.net-6.0

In .NET Core/.NET 5+, how do I set the transaction isolation level of a TransactionScope?


In .NET Core/.NET 5+, how do I set the transaction isolation level of a TransactionScope? In .NET Framework, it seems you could pass a TransactionOptions instance into the TransactionScope creation, but now it seems that isn't an option.

try {
    using (TransactionScope transaction = new(TransactionScopeAsyncFlowOption.Enabled))
    {  
        UpdateTable1();
        UpdateTable2();
        transaction.Complete();
    }
} catch { ... }

(The background: It appears that I am having deadlocks on transactions that run as SERIALIZABLE, which seems to be the default when using a C# TransactionScope, and as a partial remedy, I wonder if having READ COMMITTED on all TransactionScopes would help.)


Solution

  • Use one of the constructors accepting TransactionOptions:

    using var tr = new TransactionScope(
        TransactionScopeOption.Required, 
        new TransactionOptions
        {
            IsolationLevel = IsolationLevel.ReadCommitted
        },
        TransactionScopeAsyncFlowOption.Enabled);