DEV Community

Cover image for EF Core IDbCommandInterceptor
Maayur Dahake
Maayur Dahake

Posted on

EF Core IDbCommandInterceptor

EF Core IDbCommandInterceptor

In multi-tenant systems, forgetting to append a tenant filter in a LINQ query leads to catastrophic data leaks. While EF Core global query filters help, they often fall short when dealing with raw SQL, complex stored procedure wrappers, or decoupled microservices sharing a single context.

Instead of relying purely on convention, you can intercept the command lifecycle right before the database driver executes the query.

Before

// Easy to forget when writing ad-hoc queries
var users = db.Users
    .Where(u => u.TenantId == currentTenant)
    .ToList();
Enter fullscreen mode Exit fullscreen mode

After

public class TenantInterceptor : DbCommandInterceptor
{
    public override InterceptionResult<DbDataReader> ReaderExecuting(
        DbCommand command,
        CommandEventData eventData,
        InterceptionResult<DbDataReader> result)
    {
        // Inject tenant predicate or validate command text
        return base.ReaderExecuting(command, eventData, result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Why it matters

  • Zero Leakage: Guarantees isolation even if developers write raw SQL or forget context filters.
  • Plan Cache Impact: Modifying command text changes the SQL hash, so ensure mutations are deterministic.
  • Pipeline Integration: Registered easily in AddDbContext dependency injection setups.

Watch out

Regex string manipulation on SQL commands can corrupt complex queries containing subqueries or joins. Always validate generated execution plans under load.

How do you enforce tenancy boundaries in your data access layer?

Top comments (0)