Skip to content

EF Core Interceptor — Complete Guide

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about EF Core Interceptor. We cover key concepts, practical examples, and best practices.

You need to log every SQL query, set a command timeout globally, or audit changes. Overriding SaveChanges is not enough — you need visibility into the actual database commands sent. EF Core interceptors hook into command execution, connection management, and save changes.

Wrong

// Manual logging around every operation:
Console.WriteLine($"Executing query at {DateTime.Now}");
var data = await db.Orders.ToListAsync();
Console.WriteLine($"Query completed: {data.Count} rows");

Output: Works. But you have to wrap every operation manually. Easy to miss one.

public class LoggingInterceptor : DbCommandInterceptor
{
    public override InterceptionResult<DbDataReader> ReaderExecuting(
        DbCommand command,
        CommandEventData eventData,
        InterceptionResult<DbDataReader> result)
    {
        Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {command.CommandText}");
        return result;
    }
}

// Registration
builder.Services.AddDbContext<AppDbContext>((sp, options) =>
{
    options.UseSqlServer(connectionString)
        .AddInterceptors(new LoggingInterceptor());
});

Output: Every SQL command is logged automatically. No per-query code needed.

Other interceptor types:

// Save changes interceptor
public class AuditInterceptor : SaveChangesInterceptor
{
    public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
        DbContextEventData eventData,
        InterceptionResult<int> result,
        CancellationToken ct = default)
    {
        foreach (var entry in eventData.Context.ChangeTracker.Entries())
        {
            if (entry.State == EntityState.Modified)
                Console.WriteLine($"Modified: {entry.Entity.GetType().Name}");
        }
        return new ValueTask<InterceptionResult<int>>(result);
    }
}

Prevention

  • Use DbCommandInterceptor for SQL logging, caching, timeout management.
  • Use SaveChangesInterceptor for pre/post-save auditing and validation.
  • Use ConnectionInterceptor for connection open/close tracking.
  • Use DbTransactionInterceptor for transaction management.
  • Register multiple interceptors — they execute in registration order.
  • Make interceptors scoped if they need access to scoped services (like IHttpContextAccessor).
  • Use InterceptionResult to suppress or modify database operations.

Common Mistakes with core interceptor

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead of pattern matching, causing runtime errors on empty lists

These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

Can an interceptor modify the command?

Yes. You can modify command.CommandText, add parameters, or change command.CommandTimeout in the interceptor. Return InterceptionResult<...> to suppress the command entirely (useful for caching).

Are interceptors called for all queries?

Yes. Interceptors are called for every command executed through EF Core, including migrations, raw SQL, and LINQ queries. They are not called for ADO.NET commands executed outside EF Core.

Can I use dependency injection in interceptors?

Yes, for scoped interceptors. Register the interceptor as a scoped service: <a href="/design-patterns/builder/">builder</a>.Services.AddScoped<LoggingInterceptor>(). Then register via options.AddInterceptors(sp.GetRequiredService<LoggingInterceptor>()). Singleton interceptors cannot inject scoped services.

Interceptors power the audit trail in DodaTech's enterprise applications. For more EF Core, visit DodaTech.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro