如何在EF core 3中拦截数据库操作?

时间:2019-10-10 21:25:25

标签: c# .net-core-3.0 ef-core-3.0

如何在PostgreSQL中使用EF core 3进行数据库操作(例如选择/删除/插入/更新)之前进行拦截?

在EF core 3.0 https://docs.microsoft.com/en-gb/ef/core/what-is-new/ef-core-3.0/#interception-of-database-operations的新功能中,使用DbCommandInterceptor。但是,我找不到此类,也找不到AddInterceptors

我需要安装新的nuget还是使用特定的命名空间?

1 个答案:

答案 0 :(得分:1)

我找到了我需要的东西并成功实现了。

using System.Data.Common;
using Microsoft.EntityFrameworkCore.Diagnostics;

public class RowLevelSecurityInterceptor : DbCommandInterceptor
{
  public override InterceptionResult<DbDataReader> ReaderExecuting(
    DbCommand command,
    CommandEventData eventData,
    InterceptionResult<DbDataReader> result)
  {
    // command.CommandText += " OPTION (OPTIMIZE FOR UNKNOWN)";
    return result;
  }
}
public class MyDbContext : DbContext
{
  // previous codes
  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  {

    optionsBuilder
      .UseNpgsql(GetConnectionString())
      .AddInterceptors(new RowLevelSecurityInterceptor());
    }
  }
}
相关问题