分析 EF Core 查询缓存

mu8*_*u88 5 c# entity-framework-core

在我们的 .NET 7 应用程序中,我们看到 EF Core 事件计数器compiled-query-cache-hit-rate始终远低于 100%。根据文档,情况不应该是这样的:

如果该计数器保持稳定在 100% 以下,则表明您的应用程序可能正在执行某些破坏查询缓存的操作 - 最好对此进行调查。

我想知道如何调查此事。我能否以某种方式从 EF Core 引出该查询无法缓存且需要重新编译?

由于我们将 PostgreSQL 与数组类型映射一起使用,并且此功能似乎并不经常使用,因此以下查询让我想知道它是否可能导致问题:

public class Service
{
    internal static readonly List<ProcessState> NoReevaluationIsNeededStates = new() { ProcessState.Received };

    public async Task<int> UpdateAsync(string referencedKey)
    {
        await using MyDbContext context = await ContextFactory.CreateDbContextAsync();
        return await context.Points
            .Where(point => point.Keys.Contains(referencedKey) && !NoReevaluationIsNeededStates.Contains(point.State))
            .ExecuteUpdateAsync(entity => entity.SetProperty(point => point.State, ProcessState.Processed));
    }
}

public class Point
{
    public List<string> Keys { get; set; }

    public ProcessState State { get; set; }
}

public enum ProcessState
{
    Received,
    Processed
}
Run Code Online (Sandbox Code Playgroud)

请注意,我们的代码中还有其他几个 EF Core 查询,我没有在这里分享 - 前面的代码片段只是我能找到的最复杂的代码片段。

mu8*_*u88 1

我已经写了一篇关于它的小博客文章(请参阅此处),但长话短说:我们的 Grafana 仪表板包含这些指标值:
\n在此输入图像描述

\n

所有-1值显然都会降低平均 \xe2\x80\x8d\xe2\x99\x82\xef\xb8\x8f 并-1在尚未使用缓存时返回(GitHub 上的 EF Core 源代码),例如,如果有没有流量,因此没有数据库查询。

\n

非常感谢@svyatoslav-danyliv@Alberto的投入!

\n