c# - Entity Framework Core 读取未提交的问题

标签 c# entity-framework-core asp.net-core-2.0

我们的一个内部应用程序上有一个非常繁重的模块,它使用 SignalR 检查新通知。我们被告知我们正在数据库上创建锁,我们应该对有问题的方法进行未提交的读取。

这不是我以前必须做的事情,据我所知,默认情况下 EF 会提交记录读取。所以我将现有查询包装在另一个 using 语句中,如下所示:

    public IEnumerable<ClientUpdates> GetNotifications(int forPaId)
    {
        using (var transactionScope =
            new TransactionScope(TransactionScopeOption.Required, GetReadUncommitedTransactionOptions()))
        {
            using (var ctx = ContextFactory.CompanyDb)
            {
               // Do stuff

                transactionScope.Complete();

                return objectList;

            }
        }
    }

    private TransactionOptions GetReadUncommitedTransactionOptions()
    {
        var transactionOptions = new TransactionOptions
        {
            IsolationLevel = IsolationLevel.ReadUncommitted
        };

        return transactionOptions;
    }

这会导致以下错误消息:

InvalidOperationException: Warning as error exception for warning 'Microsoft.EntityFrameworkCore.Database.Transaction.AmbientTransactionWarning': An ambient transaction has been detected. Entity Framework Core does not support ambient transactions. See http://go.microsoft.com/fwlink/?LinkId=800142 To suppress this Exception use the DbContextOptionsBuilder.ConfigureWarnings API. ConfigureWarnings can be used when overriding the DbContext.OnConfiguring method or using AddDbContext on the application service provider.

因此我试图抑制警告:

services.AddDbContext<DbContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("MyConnectionString"));
            options.ConfigureWarnings(x => x.Ignore(RelationalEventId.AmbientTransactionWarning));
        });

导致此错误消息的结果:

NotSupportedException: Enlisting in Ambient transactions is not supported.

所以现在我有点迷路了,我可以看到其他人已经在 official issue tracker 上记录了这个问题,但我不明白实际问题是什么,以及我如何强制这个特定模块对数据进行“脏”读取,以阻止发生锁定。

最佳答案

首先,您得到的建议有点过时了。从 SQL Server 2005 开始,数据库快照实现了无锁定查询。这应该是默认设置,但我想它可能已被关闭。要进一步调查,请参阅 relevant documentation .总之,只要启用此功能,您就不必担心您的查询会创建锁。

其次,EF Core 中存在一个错误,目前该错误会阻止您拥有的代码正常工作。然而,它已经被修复,但它仍然在上游(即它还没有推出)。基本上,您现在无法做到这一点,但您很快就能做到。如果第一个解决方案不起作用,我会说等一下。

最后,假设第一个解决方案由于某种原因对您不起作用并且您绝对等不及修复推出,您总是可以简单地为使用 NOLOCK 的查询创建一个或多个存储过程。这当然是一项更手动的工作,所以我会先从您最重的查询开始。在查询之前和之后分析查询,您还可以考虑进行一些负载测试,以确保您确实为自己购买了一些东西。

关于c# - Entity Framework Core 读取未提交的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48383444/

相关文章:

c# - 发生未处理的异常后如何重新启动 Windows 服务

c# - 在有限区域内最大化子mdi

c# - Entity Framework Core - 一般设置值转换器

c# - 没有配置数据库提供程序 EF7

c# - 将 NEST 与 Elastic Search 结合使用来创建到文档字段的分析器映射

C# 将两个 tcp 套接字连接在一起

c# - 乐观锁定足以确保资金转账等操作的安全吗?

azure - 运行时 azure 应用程序服务中缺少 System.Private.ServiceModel

c# - 在 .net core api 中不使用模型验证查询参数

entity-framework - 在 EF Core 1.1 和 2.0 中使用相同的 EF 数据库路径