【问题标题】:How to intercept database operation in EF core 3?如何在 EF Core 3 中拦截数据库操作?
【发布时间】:2023-03-15 08:00:01
【问题描述】:

如何在 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 还是使用特定的命名空间?

【问题讨论】:

  • 添加Install-Package Microsoft.EntityFrameworkCore.SqlServer --version 3.0.0

标签: c# .net-core-3.0 ef-core-3.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());
    }
  }
}

【讨论】:

  • 您的示例代码出现此错误。有什么提示吗? 'InterceptionResult.Result' was called when 'InterceptionResult.HasResult' is false.
  • 这对我来说很好,对于 读取 数据的 EF Core 查询,但其他可覆盖的函数似乎都不能满足将数据写回数据库的需求。有没有其他人注意到这一点?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多