Course contentsShow
← C#
Lesson 1127 of 1,90810. Entity Framework Core ModelingFree lesson

Implementing Entity Interceptors

Inject logic into the SaveChanges flow for business validation or automated auditing.

In this lesson, you will learn how to automate cross-cutting concerns like auditing and validation by tapping into the SaveChanges lifecycle using EF Core Interceptors.

The Core Concept: Intercepting the Flow

Think of Entity Interceptors as "hooks" that allow you to inject custom logic exactly when EF Core is preparing to send changes to the database. Instead of manually setting properties like CreatedAt or LastModified in every service or controller, you can centralize this logic. By implementing the ISaveChangesInterceptor interface, you gain control over the SavingChangesAsync method, allowing you to inspect, modify, or even block changes before they reach the database engine.

Implementation Illustration

To automate an auditing workflow, you create a class that inherits from SaveChangesInterceptor. Here is how you might intercept the SaveChanges pipeline to automatically timestamp entities:

public class AuditInterceptor : SaveChangesInterceptor
{
    public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
        DbContextEventData eventData, 
        InterceptionResult<int> result, 
        CancellationToken ct = default)
    {
        var context = eventData.Context;
        var entries = context.ChangeTracker.Entries<IAuditable>();

        foreach (var entry in entries)
        {
            if (entry.State == EntityState.Added)
            {
                entry.Entity.CreatedAt = DateTime.UtcNow;
            }
            entry.Entity.UpdatedAt = DateTime.UtcNow;
        }

        return base.SavingChangesAsync(eventData, result, ct);
    }
}

Why Use Interceptors?

The beauty of this approach is its decoupling. Your business services no longer need to know about "auditing" or "soft delete" logic; they simply perform their work on entities, and the interceptor quietly handles the house-keeping behind the scenes. Once your class is defined, you register it in your DbContext configuration:

protected override void OnConfiguring(DbContextOptionsBuilder options)
    => options.AddInterceptors(new AuditInterceptor());

By leveraging these interceptors, you ensure that your business validation and audit rules are applied consistently across the entire application, eliminating the risk of human error in your data access layer.

Key Takeaway: Entity Interceptors allow you to centralize cross-cutting logic like auditing and validation by intercepting the SaveChanges process, ensuring consistent data integrity without cluttering your business logic.