EF Core 在 3.x 版本中增长了 Interceptor
,使得咱们能够在发生低级别数据库操做时做为 EF Core 正常运行的一部分自动调用它们。 例如,打开链接、提交事务或执行命令时。git
因此咱们能够自定义一个 Interceptor
来记录执行的 sql 语句,也能够经过 Interceptor
来实现 sql 语句的执行。github
这里咱们能够借助 Interceptor
实现对于查询语句的修改,自动给查询语句加 (WITH NOLOCK)
,WITH NOLOCK
等效于 READ UNCOMMITED
(读未提交)的事务级别,这样会形成必定的脏读,可是从效率上而言,是比较高效的,不会由于别的事务长时间未提交致使查询阻塞,因此对于大数据场景下,查询 SQL 加 NOLOCK
仍是比较有意义的sql
继承 DbCommandInterceptor
,重写查询 sql 执行以前的操做,在执行 sql 以前增长 WITH(NOLOCK)
,实现代码以下:数据库
public class QueryWithNoLockDbCommandInterceptor : DbCommandInterceptor { private static readonly Regex TableAliasRegex = new Regex(@"(?<tableAlias>AS \[[a-zA-Z]\w*\](?! WITH \(NOLOCK\)))", RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.IgnoreCase); public override InterceptionResult<object> ScalarExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<object> result) { command.CommandText = TableAliasRegex.Replace( command.CommandText, "${tableAlias} WITH (NOLOCK)" ); return base.ScalarExecuting(command, eventData, result); } public override Task<InterceptionResult<object>> ScalarExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<object> result, CancellationToken cancellationToken = new CancellationToken()) { command.CommandText = TableAliasRegex.Replace( command.CommandText, "${tableAlias} WITH (NOLOCK)" ); return base.ScalarExecutingAsync(command, eventData, result, cancellationToken); } public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result) { command.CommandText = TableAliasRegex.Replace( command.CommandText, "${tableAlias} WITH (NOLOCK)" ); return result; } public override Task<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = new CancellationToken()) { command.CommandText = TableAliasRegex.Replace( command.CommandText, "${tableAlias} WITH (NOLOCK)" ); return base.ReaderExecutingAsync(command, eventData, result, cancellationToken); } }
在注册 DbContext
服务的时候,能够配置 Interceptor
,配置以下:ide
var services = new ServiceCollection(); services.AddDbContext<TestDbContext>(options => { options .UseLoggerFactory(loggerFactory) .UseSqlServer(DbConnectionString) .AddInterceptors(new QueryWithNoLockDbCommandInterceptor()) ; });
经过 loggerFactory 记录的日志查看查询执行的 sql 语句大数据
能够看到查询语句自动加上了 WITH (NOLOCK)
日志