EF Core 3.1 在 DbContext

问题描述

我需要对 DbContext 执行的所有操作应用相同的 IsolationLevel,所以我不必每次使用它时都指定它。 有什么办法吗?

我正在使用 EF Core 3.1 和 sqlServer

更新:经过一些研究和测试后,我发现我正在寻找的是将 WITH (NOLOCK) 应用于表。此外,我尝试将事务范围应用于单个查询,并尝试从锁定的表中读取数据,但它不起作用。

这是我使用的代码

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

// query execution

transactionScope.Complete();

代码已复制自:https://docs.microsoft.com/en-gb/ef/core/saving/transactions,唯一的区别在于 IsolationLevel。

解决方法

EF Core 是一个可以针对多个数据源运行的 ORM,并非所有数据源都改变事务隔离级别,因此,在 EF 中,此属性是只读的。如果要为 SQL Server 更改它,则需要在 T-Sql 代码中进行。

,

您应该在 Dotnet 核心中间件的责任链中执行此操作。 在每个动作执行之前,您可以启动一个事务范围并设置事务隔离级别,并在动作执行后结束它。在此处查看中间件和 dotnet 管道:

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

这种模式与工作单元实现非常相似。

,

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

我有这个我能找到的最好的解决方案,即使在我看来还不够好。

它会生成此警告,可能会为将来的更新带来一些问题。

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.

我没有采用它,但目前这是我能找到的唯一方法来达到在不锁定任何表的情况下读取未提交数据的目标。