Audit columns in EF Core 10 with an IAuditable interface, a SaveChangesInterceptor, TimeProvider and a current-user service; lifetimes with pooling, gaps (ExecuteUpdate, raw SQL), testing, and temporal tables as the alternative.
Entities implement IAuditable (CreatedAt, CreatedBy, ModifiedAt, ModifiedBy). A SaveChangesInterceptor walks the change tracker: for Added entries it sets the created fields, for Modified entries the modified fields, and it marks the created fields as not modified so updates cannot change them. Time comes from TimeProvider so tests can freeze it; the user comes from a scoped current-user service.
It misses anything that skips the change tracker: ExecuteUpdate, raw SQL and other tools. And audit columns only tell you who last touched a row, not what changed. When you need full history, SQL Server temporal tables keep every version, at the cost of storage and without the app user unless you add it.
"Audit columns are cross-cutting, so they belong in one place, not in every handler. I put an
IAuditableinterface on the entities and write aSaveChangesInterceptor. InSavingChangesAsyncit loops overChangeTracker.Entries<IAuditable>(): onAddedit setsCreatedAtandCreatedBy, onModifiedit setsModifiedAtandModifiedBy, and it setsIsModified = falseon the created properties so an update that maps a whole DTO can't overwrite them. The time comes fromTimeProvider, which is in the base library since .NET 8, so in tests I swap inFakeTimeProviderand assert exact timestamps.The user comes from a scoped
ICurrentUserthat reads the validated principal, and background jobs set a system identity likejob:invoice-run. For example, at [company] we replaced [about 40] handlers that each setModifiedAt = DateTime.Nowin local server time. Moving it into one interceptor fixed [timezone bugs between Australia East and our UTC containers] and deleted [a few hundred] lines of repeated code.The mistake I see is treating audit columns as an audit trail. They tell you who last changed a row, not what changed, and they're blind to
ExecuteUpdate, raw SQL and anyone with SSMS. If a regulator or a customer dispute needs history, I use SQL Server temporal tables, or an append-only audit log written in the same transaction. Audit columns answer 'who touched this last'; history needs a history mechanism."
| Approach | What you get | Covers non-EF writes? | Cost |
|---|---|---|---|
| Audit columns via interceptor | Created/modified who and when | No | Four columns |
| Temporal tables | Every version of every row, with period columns | Yes (database level) | History table storage |
| Audit log table (interceptor writes diffs) | Who changed which property from what to what | No | Extra writes, design effort |
| SQL Server Audit / CDC | Database-level events or changes | Yes | Operations, storage |
| Registration | DbContext options lifetime | Interceptor can be |
|---|---|---|
AddDbContext |
Scoped (per context) | Scoped, resolved from sp |
AddDbContextPool / pooled factory |
Singleton | Singleton; read the user via IHttpContextAccessor at save time |
In a [claims processing system], centralising audit columns into an interceptor removed [~300] lines from handlers, and a test suite with FakeTimeProvider caught a bug where CreatedAt was being overwritten by updates on [3] endpoints that used Update() with a mapped DTO.
Checks that the candidate centralises cross-cutting persistence logic correctly and knows the limits of audit columns.
Green flags
TimeProvider and a current-user abstractionExecuteUpdate and raw SQL as gaps, and temporal tables for historyRed flags
DateTime.Now in every handlerSaveChangesAsync
├─ DetectChanges (states computed)
├─ SavingChangesAsync ◀── interceptor sets audit values here
├─ (DetectChanges again for values changed by interceptors)
├─ Commands built and batched
└─ SavedChangesAsync / SaveChangesFailedAsync
The interceptor runs after DetectChanges, so entry states are already known. Setting a property on a tracked entity in SavingChanges is picked up because EF Core detects changes for the values you set.
A common API pattern loads an entity and maps an entire DTO onto it, or calls Update() on a detached entity, which marks every property as modified, including CreatedAt with a default value. Setting entry.Property(x => x.CreatedAt).IsModified = false excludes those columns from the UPDATE.
DateTimeOffset in UTC, mapped to datetimeoffset or datetime2 with UTC by convention.TimeProvider.System.GetUtcNow() in production, FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing) in tests.DateTime.Now: containers run in UTC, developers in AEST/AEDT, and daylight saving creates duplicate local times.HTTP: ClaimsPrincipal (validated) → ICurrentUser.Id
Job: explicit identity, e.g. "system:payroll-import"
Store a stable id (the oid or sub claim), not an email that can change, and avoid writing personal information into many tables unnecessarily.
SQL Server system-versioned temporal tables keep a history table with PeriodStart/PeriodEnd. EF Core maps them with ToTable(t => t.IsTemporal()) and queries them with TemporalAsOf, TemporalAll, TemporalBetween. They capture every change from any client, but not the application user: you add a ModifiedBy column (still set by the interceptor) so each historical version carries it.
ExecuteUpdate/ExecuteDelete: set the columns in the call, e.g. .SetProperty(x => x.ModifiedAt, now).ExecuteSql and stored procedures.FakeTimeProvider that advances time between create and update.Update() on a detached entity with CreatedAt = default and check the generated SQL with and without IsModified = false.AddDbContextPool and see why a scoped interceptor no longer resolves.TemporalAll() after three updates.An audit interceptor using TimeProvider and a current-user abstraction:
namespace Claims.Infrastructure;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
public interface IAuditable
{
DateTimeOffset CreatedAt { get; set; }
string CreatedBy { get; set; }
DateTimeOffset? ModifiedAt { get; set; }
string? ModifiedBy { get; set; }
}
public interface ICurrentUser { string Id { get; } }
// Works as a singleton: reads the user at save time, so it is safe with DbContext pooling too.
public sealed class HttpCurrentUser(IHttpContextAccessor accessor) : ICurrentUser
{
public string Id => accessor.HttpContext?.User.FindFirstValue("oid") ?? "system";
}
public sealed class AuditInterceptor(TimeProvider clock, ICurrentUser user) : SaveChangesInterceptor
{
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken ct = default)
{
var now = clock.GetUtcNow();
foreach (var entry in eventData.Context!.ChangeTracker.Entries<IAuditable>())
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatedAt = now;
entry.Entity.CreatedBy = user.Id;
break;
case EntityState.Modified:
entry.Entity.ModifiedAt = now;
entry.Entity.ModifiedBy = user.Id;
// An Update() of a mapped DTO marks everything modified; never overwrite creation data.
entry.Property(e => e.CreatedAt).IsModified = false;
entry.Property(e => e.CreatedBy).IsModified = false;
break;
}
}
return base.SavingChangesAsync(eventData, result, ct);
}
}
// Program.cs
builder.Services.AddHttpContextAccessor();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddSingleton<ICurrentUser, HttpCurrentUser>();
builder.Services.AddSingleton<AuditInterceptor>();
builder.Services.AddDbContextPool<ClaimsDbContext>((sp, options) => options
.UseSqlServer(builder.Configuration.GetConnectionString("Claims"))
.AddInterceptors(sp.GetRequiredService<AuditInterceptor>()));
A test with FakeTimeProvider (package Microsoft.Extensions.TimeProvider.Testing):
namespace Claims.Tests;
using Claims.Infrastructure;
using Microsoft.Extensions.Time.Testing;
using Xunit;
public sealed class AuditInterceptorTests(SqlServerFixture fixture) : IClassFixture<SqlServerFixture>
{
private sealed record FixedUser(string Id) : ICurrentUser;
[Fact]
public async Task Update_sets_modified_and_keeps_created()
{
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 11, 19, 0, 0, 0, TimeSpan.Zero));
await using var db = fixture.CreateContext(new AuditInterceptor(clock, new FixedUser("alice")));
var claim = new Claim { Reference = "C-1" };
db.Add(claim);
await db.SaveChangesAsync();
clock.Advance(TimeSpan.FromHours(2));
claim.Reference = "C-1a";
await db.SaveChangesAsync();
Assert.Equal(new DateTimeOffset(2026, 11, 19, 0, 0, 0, TimeSpan.Zero), claim.CreatedAt);
Assert.Equal(new DateTimeOffset(2026, 11, 19, 2, 0, 0, TimeSpan.Zero), claim.ModifiedAt);
Assert.Equal("alice", claim.ModifiedBy);
}
}
Bulk updates bypass the interceptor, so set the columns explicitly:
await db.Claims
.Where(c => c.Status == ClaimStatus.Stale)
.ExecuteUpdateAsync(s => s
.SetProperty(c => c.Status, ClaimStatus.Closed)
.SetProperty(c => c.ModifiedAt, clock.GetUtcNow())
.SetProperty(c => c.ModifiedBy, "system:stale-claims"), ct);
SaveChangesInterceptor.DateTime.Now. Why it is wrong: Containers run in UTC and developers in AEST/AEDT, so values are inconsistent and daylight saving creates ambiguity. Instead: TimeProvider.GetUtcNow() with DateTimeOffset.CreatedAt/CreatedBy on update. Why it is wrong: Update() on a mapped DTO overwrites them with defaults. Instead: Set IsModified = false on those properties.AddDbContextPool. Why it is wrong: Pooled options are singletons, so resolution fails or captures one request's user. Instead: Make the interceptor singleton and read the user at save time.ExecuteUpdate is audited. Why it is wrong: It bypasses the change tracker and interceptors. Instead: Set the audit columns in SetProperty.CreatedBy. Why it is wrong: Emails change and spread personal information. Instead: Store a stable user id.Ask what question the audit data must answer. "Who last edited this record?" is audit columns. "What did this record look like on 1 July?" is temporal tables. "Who changed the bank account number from X to Y?" is an audit log with property-level diffs, written in the same transaction. Many regulated Australian systems (health, finance) need the third, and auditors will ask whether it can be bypassed.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Audit columns | Last-touched info for support | Minimal | Disputes, compliance history |
| Temporal tables | Point-in-time reads, restore | History storage, retention policy needed | Need to record the app user alone |
| Audit log table | Field-level who/what/when | More writes, schema design | Low-value tables |
| SQL Server Audit / CDC | Database-level, covers every client | Operations | App-level context (user, request) |
Use a SaveChangesInterceptor (registered with AddInterceptors) that, in SavingChanges/SavingChangesAsync, walks ChangeTracker.Entries<IAuditable>() (or every entry that has the columns) and sets CreatedAt/CreatedBy for Added entries and ModifiedAt/ModifiedBy for Modified ones. Get the time from an injected TimeProvider so tests can fake it, and the user from a scoped ICurrentUser service that reads HttpContext.User (or the message's identity in a background worker). If you don't want audit fields on the domain classes, map them as shadow properties (builder.Property<DateTimeOffset>("CreatedAt")) and set them with entry.Property("CreatedAt").CurrentValue. Mark CreatedAt as not modified on updates so it can't be overwritten. Note that ExecuteUpdate and raw SQL bypass the interceptor; use temporal tables when you need full history, not just the last change.
Interceptors let you run code before and after EF Core operations without touching every call site. The main ones are DbCommandInterceptor (see or change the SQL, time it, or suppress execution and return a cached result), SaveChangesInterceptor (inspect the ChangeTracker in SavingChangesAsync to set audit columns, turn deletes into soft deletes or write outbox rows), and DbConnectionInterceptor (run code as a connection opens, such as setting SESSION_CONTEXT for row-level security). You register them with AddInterceptors, usually resolved from DI. With AddDbContextPool they behave like singletons, so they must not capture scoped services. They don't see everything: ExecuteUpdate/ExecuteDelete bypass SaveChanges interceptors. The trade-off is central, invisible behaviour versus surprise for anyone reading a handler, so keep them few, fast and documented.
A system-versioned temporal table makes SQL Server copy the previous version of a row into a history table on every UPDATE and DELETE, stamping period columns (PeriodStart/PeriodEnd, UTC). Since EF Core 6 you configure it with ToTable(t => t.IsTemporal()); the period columns become shadow properties and migrations create the history table. You query history with TemporalAsOf(utc), TemporalAll(), TemporalFromTo, TemporalBetween and TemporalContainedIn, which return untracked results; restoring a deleted row is a TemporalAsOf query followed by Add. Temporal tables record what and when, not who, so you still need a ModifiedBy column. The trade-off: point-in-time history for free in code, paid for in history storage that grows with every update and needs a retention policy.
How to tell it (STAR)
**S:** At [company] our claims API set audit columns through an EF Core interceptor. **T:** A dashboard suddenly showed [12,000] claims created in year 1, and I was asked to fix the data and the cause. **A:** EF Core logs showed an endpoint calling `Update()` on a mapped DTO, which overwrote the created fields with defaults. I restored the values from the temporal history table, changed the interceptor to protect created fields, and added a test and a CHECK constraint. **R:** All [12,000] rows were restored the same day, and the constraint has since blocked [a couple of] similar bugs in testing.
Last updated 23 Nov 2026.