什么是查询拦截器?在EF Core中如何使用它?

来源:这里教程网 时间:2026-02-21 17:28:01 作者:

查询拦截器是一种允许你在EF Core中拦截数据库操作的功能,主要用于修改或记录查询执行过程中的行为。它属于EF Core的拦截机制(Interception)的一部分,能够让你在不改变业务代码的前提下,对查询进行审计、日志记录、数据过滤或性能监控等操作。

查询拦截器的作用

查询拦截器可以捕获与数据库相关的操作,比如:

SQL 查询语句的生成和执行 命令的执行时间 连接的打开与关闭

通过实现自定义逻辑,你可以在查询发送到数据库之前或之后进行处理,例如添加默认过滤条件、记录慢查询或实现多租户数据隔离。

如何在EF Core中使用查询拦截器

要在EF Core中使用查询拦截器,需要创建一个类继承 DbCommandInterceptor,并重写相关方法。然后在 DbContext 配置时注册该拦截器。

1. 创建自定义拦截器

下面是一个简单的例子,用于记录所有执行时间超过一定阈值的查询:

using Microsoft.EntityFrameworkCore.Diagnostics;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
public class QueryLoggingInterceptor : DbCommandInterceptor
{
    private readonly Stopwatch _stopwatch = new Stopwatch();
    public override InterceptionResult<DbDataReader> ReaderExecuting(
        DbCommand command,
        CommandEventData eventData,
        InterceptionResult<DbDataReader> result)
    {
        _stopwatch.Restart();
        return result;
    }
    public override async ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
        DbCommand command,
        CommandEventData eventData,
        InterceptionResult<DbDataReader> result,
        CancellationToken cancellationToken = default)
    {
        _stopwatch.Restart();
        return result;
    }
    public override DbDataReader ReaderExecuted(DbCommand command, CommandEventData eventData, DbDataReader result)
    {
        _stopwatch.Stop();
        if (_stopwatch.ElapsedMilliseconds > 1000)
        {
            Console.WriteLine($"慢查询警告:{command.CommandText}");
            Console.WriteLine($"耗时:{_stopwatch.ElapsedMilliseconds} 毫秒");
        }
        return result;
    }
    public override async Task<DbDataReader> ReaderExecutedAsync(DbCommand command, CommandEventData eventData, DbDataReader result, CancellationToken cancellationToken = default)
    {
        _stopwatch.Stop();
        if (_stopwatch.ElapsedMilliseconds > 1000)
        {
            Console.WriteLine($"异步慢查询警告:{command.CommandText}");
            Console.WriteLine($"耗时:{_stopwatch.ElapsedMilliseconds} 毫秒");
        }
        return result;
    }
}

2. 在 DbContext 中注册拦截器

Program.csStartup.cs 中配置 EF Core 服务时,使用 AddInterceptors 方法注册拦截器:

services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString)
           .AddInterceptors(new QueryLoggingInterceptor()));

常见应用场景

查询拦截器适用于多种实际场景:

日志记录:自动记录所有数据库命令及其执行时间。 性能监控:识别并告警长时间运行的查询。 多租户支持:在查询中动态添加租户ID过滤条件(需结合其他技术如全局过滤器)。 数据脱敏或审计:在特定环境下修改查询结果或记录访问行为。

基本上就这些。查询拦截器是EF Core中强大而灵活的工具,合理使用能提升系统的可观测性和安全性。注意不要在拦截器中执行耗时操作,以免影响整体性能。

相关推荐