In this lesson, you will learn how to hook into the Entity Framework Core pipeline to inspect, log, or even modify database commands before they reach your database.
What are Database Interceptors?
Database Interceptors are essentially "middleware" for your data access layer. They allow you to define logic that runs automatically whenever EF Core executes a command, such as querying data, opening a connection, or saving changes. Instead of manually writing logging code or repeating audit logic across your service layer, you define an interceptor once, and EF Core handles the rest.
How it Works
To create an interceptor, you implement the IDbCommandInterceptor interface (or inherit from DbCommandInterceptor for convenience). You can override methods like ReaderExecuting (before a query runs) or NonQueryExecuted (after a non-query command finishes).
For example, if you want to log every SQL command generated by your application, you can override ReaderExecuting:
public class MyCommandInterceptor : DbCommandInterceptor
{
public override InterceptionResult<DbDataReader> ReaderExecuting(
DbCommand command,
CommandEventData eventData,
InterceptionResult<DbDataReader> result)
{
Console.WriteLine($"Executing command: {command.CommandText}");
return base.ReaderExecuting(command, eventData, result);
}
}
Once defined, you register the interceptor in your DbContext configuration:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(connectionString)
.AddInterceptors(new MyCommandInterceptor());
}
Why Use Them?
Interceptors are incredibly powerful because they operate at the very bottom of the EF Core stack. Beyond logging, you can use them for:
- Auditing: Automatically attaching "CreatedBy" or "ModifiedDate" values to entities before they are saved.
- Dynamic SQL Modification: Injecting query hints (like
WITH (NOLOCK)) into SQL strings for performance tuning. - Security: Masking sensitive data or enforcing row-level security policies at the database driver level.
By decoupling these cross-cutting concerns from your business logic, your domain code remains clean and focused solely on your application requirements.
Key Takeaway: Database Interceptors allow you to centralize logic for logging, auditing, and command modification by hooking directly into the EF Core command execution pipeline.