Search code examples
c#sql-serverdbcontextef-core-3.1isolation-level

EF Core 3.1 set default IsolationLevel in DbContext


I need to apply the same IsolationLevel to all the operation executed by the DbContext, so I don't have to specify it each time I use it. Is there any way to do it?

I'm working with EF Core 3.1 and SqlServer

UPDATE: after some research and tests I found out that what I'm looking for is to apply WITH (NOLOCK) to the tables. Also I tried to apply the transaction scope to a single query and tried to read data from a locked table and it is not working.

This is the code I used:

using var transactionScope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted });

// query execution

transactionScope.Complete();

This code have been copied from: https://learn.microsoft.com/en-gb/ef/core/saving/transactions, the only difference is on the IsolationLevel.


Solution

  • https://stackoverflow.com/a/53082098/12919581

    I have this solution that is the best I could found, even if in my opinion is not good enought.

    It generates this warning that could create some problems for future update.

    Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerQuerySqlGenerator is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release.

    I'm not adopting it, but at the moment it is the only way I could found to reach the goal of reading uncommitted data without locking any table.