简体   繁体   中英

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://docs.microsoft.com/en-gb/ef/core/saving/transactions , the only difference is on the IsolationLevel.

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.

EF Core is an ORM that can run against multiple data sources, not all of them changing transaction isolation level, because of this, in EF this property is readonly. If you want to change it for SQL Server, you will need to do it from within your T-Sql code.

You should do it inside the chain-of-responsibility of Dotnet core middlewares. before each action execution, you can start a transaction scope and set transaction isolation level and, end it after action execution. See middlewares and dotnet pipelines here:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
       app.Use(async (context, next) =>
       {
           //begin your transaction scope.
           await next.Invoke();
           //finalize the corresponding scope.
       });
    }
 }

this pattern is very similar to unit-of-work implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM