Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept database operation in EF core 3?

How do I intercept before the database operation like select/delete/insert/update using EF core 3 in PostgreSQL?

In the new feature of EF core 3.0 https://docs.microsoft.com/en-gb/ef/core/what-is-new/ef-core-3.0/#interception-of-database-operations, DbCommandInterceptor is used for that. However, I couldn't find this class nor the AddInterceptors.

Do I need to install new nuget or using specific namespace?

like image 501
Suwarno Ong Avatar asked Oct 10 '19 21:10

Suwarno Ong


People also ask

What types of database interaction does the EF6 interceptor class allow you to intercept?

Entity Framework Core (EF Core) interceptors enable interception, modification, and/or suppression of EF Core operations. This includes low-level database operations such as executing a command, as well as higher-level operations, such as calls to SaveChanges.

Is scaffold DbContext command is used in EF Code First approach?

Entity Framework Core supports Database-First approach via the Scaffold-DbContext command of Package Manager Console. This command scaffolds a DbContext and entity type classes for a specified database.

Is EF core faster than EF6?

Entity Framework (EF) Core, Microsoft's object-to-database mapper library for . NET Framework, brings performance improvements for data updates in version 7, Microsoft claims. The performance of SaveChanges method in EF7 is up to 74% faster than in EF6, in some scenarios.


1 Answers

I have found what I need and successfully implemented.

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());
    }
  }
}
like image 173
Suwarno Ong Avatar answered Sep 28 '22 18:09

Suwarno Ong