EF Core Interceptor — Complete Guide
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.
Right
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
DbCommandInterceptorfor SQL logging, caching, timeout management. - Use
SaveChangesInterceptorfor pre/post-save auditing and validation. - Use
ConnectionInterceptorfor connection open/close tracking. - Use
DbTransactionInterceptorfor transaction management. - Register multiple interceptors — they execute in registration order.
- Make interceptors scoped if they need access to scoped services (like
IHttpContextAccessor). - Use
InterceptionResultto suppress or modify database operations.
Common Mistakes with core interceptor
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead 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
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