In EF Core 10, how do you stamp CreatedAt and UpdatedAt on every save, and which writes would that stamping miss?
answer
- SaveChangesInterceptor, sync and async
- AddInterceptors on the options
- ChangeTracker.Entries<T>() detects changes
- IsModified = false keeps CreatedAt
- ExecuteUpdate bypasses SaveChanges
basics
~20 sOverride SavingChanges and SavingChangesAsync in a SaveChangesInterceptor registered with AddInterceptors, then set CreatedAt on Added entries and UpdatedAt on Modified ones from ChangeTracker.Entries. ExecuteUpdate, ExecuteDelete and raw SQL never pass through SaveChanges, so they are not stamped.
solid answer
~40 sAudit stamps belong where every save passes: a `SaveChangesInterceptor` overriding both `SavingChanges` and `SavingChangesAsync`, registered with `options.AddInterceptors(...)`. Inside, `eventData.Context!.ChangeTracker.Entries<IAuditable>()` - which runs change detection first, so states are current - lets you set `CreatedAt` on `Added` entries and `UpdatedAt` on `Modified` ones, and mark `CreatedAt` unmodified so an update can never overwrite it. Overriding `SaveChangesAsync` in the context or handling the `DbContext.SavingChanges` event works too; the interceptor keeps the concern out of the context and can be shared. Take time from an injected `TimeProvider` so tests can control it. The gap: `ExecuteUpdateAsync`, `ExecuteDeleteAsync` and raw SQL write without the change tracker, so they skip every one of these hooks and must set stamps themselves.
code
csharp · 6 linesbuilder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<AuditStampInterceptor>();
builder.Services.AddDbContext<OrderingContext>((sp, options) => options
.UseNpgsql(builder.Configuration.GetConnectionString("Ordering"))
.AddInterceptors(sp.GetRequiredService<AuditStampInterceptor>()));go deeper
Know that audit columns are best set in one place on save, not in every handler.
Implement a SaveChangesInterceptor with both sync and async overrides, register it with AddInterceptors, and stamp from ChangeTracker.Entries by state.
Name the writes that bypass SaveChanges, protect CreatedAt on updates, keep the interceptor stateless and the clock injectable.
Decide whether stamps live in the application, the database, or both, given other writers and bulk updates that skip EF Core's hooks.
## The goal Every row in a bakery chain's ordering database carries `CreatedAt` and `UpdatedAt`. Setting them by hand in each handler is forgotten sooner or later; the dependable place is the single point every tracked write passes through - `SaveChanges`. ## Three hooks around SaveChanges | Hook | Where it lives | Notes | |---|---|---| | override `SaveChanges` / `SaveChangesAsync` | in your `DbContext` subclass | simple; the logic is tied to one context type | | `DbContext.SavingChanges` event | subscribed in the context's constructor | synchronous `EventHandler`, no async work | | `ISaveChangesInterceptor` / `SaveChangesInterceptor` | a separate class added through options | sync and async methods, reusable across contexts, can suppress or change the result | `SaveChangesInterceptor` is a base class with no-op implementations of `SavingChanges`, `SavingChangesAsync`, `SavedChanges`, `SavedChangesAsync`, `SaveChangesFailed` and `SaveChangesFailedAsync`. **Override both the sync and the async `Saving` methods**: `SaveChanges` calls only the sync one, `SaveChangesAsync` only the async one, and the base class does nothing in the one you forget. ## A stamping interceptor ```csharp public sealed class AuditStampInterceptor(TimeProvider clock) : SaveChangesInterceptor { public override InterceptionResult<int> SavingChanges( DbContextEventData eventData, InterceptionResult<int> result) { Stamp(eventData.Context); return result; } public override ValueTask<InterceptionResult<int>> SavingChangesAsync( DbContextEventData eventData, InterceptionResult<int> result, CancellationToken ct = default) { Stamp(eventData.Context); return ValueTask.FromResult(result); } private void Stamp(DbContext? db) { if (db is null) return; var now = clock.GetUtcNow(); foreach (var e in db.ChangeTracker.Entries<IAuditable>()) { if (e.State == EntityState.Added) e.Entity.CreatedAt = now; if (e.State is EntityState.Added or EntityState.Modified) e.Entity.UpdatedAt = now; if (e.State == EntityState.Modified) e.Property(x => x.CreatedAt).IsModified = false; } } } ``` Details that matter: - **Timing.** EF Core raises `SavingChanges` and calls the interceptor's `SavingChanges` *before* its own change detection. Enumerating `ChangeTracker.Entries<T>()` runs detection itself, so an entity whose only edit was a property assignment is already `Modified` by the time you check its state. - **`CreatedAt` protection.** For an entity attached with `Update`, every property is marked modified - including a `CreatedAt` the client may have sent as default. Setting `IsModified = false` keeps the stored value. - **Registration.** `options.AddInterceptors(interceptor)` in `AddDbContext`. With the `(serviceProvider, options)` overload of `AddDbContext` you can resolve the interceptor from DI, for example registered as a singleton because it is stateless. - **State.** The EF Core docs note that interceptors are often stateless and one instance can serve every context; an interceptor that keeps per-save state (like the docs' auditing example that stores an audit record between `SavingChanges` and `SavedChanges`) needs a new instance per context. - **Testable time.** `TimeProvider` lets a test pin the clock. ## What the stamps will miss Anything that does not go through the change tracker and `SaveChanges`: - **`ExecuteUpdateAsync` / `ExecuteDeleteAsync`** send SQL straight away and never touch the tracker, so no `SavingChanges` hook runs. Add `s.SetProperty(x => x.UpdatedAt, now)` to the setters yourself. - **Raw SQL** through `Database.ExecuteSqlAsync` or `FromSql`-based writes. - **Other writers** - another service, a migration script, a database job. Only a database default or trigger covers those. - **Changes made inside `SavedChanges`**: they come after the save and are not written by it. ## Common mistakes - Overriding only `SavingChangesAsync`, then a background job calls `SaveChanges` and nothing is stamped. - Reading `DateTime.Now` (local time, untestable) instead of a UTC value from `TimeProvider`. - Setting `UpdatedAt` on `Unchanged` entries, turning every save into an update of every tracked row.
- A nightly job marks stale orders cancelled with ExecuteUpdateAsync, and their UpdatedAt never changes. Why, and what do you do?`ExecuteUpdateAsync` runs one `UPDATE` immediately without the change tracker or `SaveChanges`, so no saving interceptor or event fires. Set the stamp in the same call - `.ExecuteUpdateAsync(s => s.SetProperty(o => o.Status, OrderStatus.Cancelled).SetProperty(o => o.UpdatedAt, now))` - or rely on a database trigger if every writer must be covered.
- When an interceptor's SavingChanges runs, has EF Core already detected the handler's property edits?Not yet: `SaveChanges` raises the `SavingChanges` event and calls the interceptor before its own change detection. Enumerating `ChangeTracker.Entries<T>()` runs detection first while `AutoDetectChangesEnabled` is on, so states read through it are current; with automatic detection off, call `ChangeTracker.DetectChanges()` before reading states.
- Overriding SavingChangesAsync alone also covers synchronous SaveChanges calls.
- ExecuteUpdateAsync runs the SaveChanges interceptors, so its rows get stamped.
- Every interceptor must be registered as a new instance per DbContext.
- Changes made in SavedChanges are written by the same SaveChanges call.
- Setting UpdatedAt on Unchanged entries is harmless.