📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you set audit columns like CreatedAt and CreatedBy automatically in EF Core?

Mid-Level Theory Intermediate

🎯 Key points

  • SaveChangesInterceptor in SavingChanges/SavingChangesAsync
  • Added → CreatedAt/By; Modified → ModifiedAt/By
  • TimeProvider injected for testable timestamps
  • Scoped ICurrentUser from HttpContext.User or the message identity
  • Shadow properties keep audit columns off the domain classes
  • Protect CreatedAt on updates (IsModified = false)
  • ExecuteUpdate and raw SQL bypass interceptors
  • Temporal tables for full history

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"I put it in one place: a SaveChangesInterceptor. Before EF Core builds commands, the interceptor looks at the change tracker. For every Added entry it sets CreatedAt and CreatedBy; for every Modified entry it sets ModifiedAt and ModifiedBy, and forces CreatedAt to IsModified = false so a client can't overwrite it through a mapped DTO.

The time comes from TimeProvider, not DateTime.UtcNow, so tests can use FakeTimeProvider. The user comes from a scoped ICurrentUser that reads the sub or oid claim from HttpContext.User; in a worker, the same interface is filled from the message. Because the interceptor needs scoped services, I register it as scoped and add it with options.AddInterceptors(sp.GetRequiredService<AuditInterceptor>()).

Whether the columns live on the entity or as shadow properties is a design choice. Shadow properties keep persistence concerns off the domain model; the interceptor sets them via entry.Property(\"CreatedAt\").CurrentValue. The limits I always mention: ExecuteUpdate, ExecuteDelete and raw SQL skip the change tracker, so they skip the interceptor too, and these columns only record the last change. If auditors need full history, I add temporal tables."


public sealed class AuditInterceptor(TimeProvider clock, ICurrentUser user) : SaveChangesInterceptor
{
    public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
        DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
    {
        var now = clock.GetUtcNow();
        foreach (var entry in eventData.Context!.ChangeTracker.Entries<IAuditable>())
        {
            if (entry.State == EntityState.Added)
            {
                entry.Property("CreatedAt").CurrentValue = now;
                entry.Property("CreatedBy").CurrentValue = user.Id;
            }
            else if (entry.State == EntityState.Modified)
            {
                entry.Property("CreatedAt").IsModified = false;
                entry.Property("ModifiedAt").CurrentValue = now;
                entry.Property("ModifiedBy").CurrentValue = user.Id;
            }
        }
        return base.SavingChangesAsync(eventData, result, cancellationToken);
    }
}

Options

Approach Fits Limit
Interceptor + properties Most apps Last change only; bypassed by bulk SQL
Interceptor + shadow properties Clean domain model Need EF.Property<T> to query them
Temporal tables Full history, point-in-time queries Storage, no 'who' column by default
SQL defaults / triggers Also catches raw SQL No app user without session context

Production example

Replacing [30] hand-written entity.ModifiedAt = DateTime.Now lines with one interceptor fixed [local-time] timestamps in a system hosted in Australia East and made the audit columns consistent across every table.

🔍 What the interviewer is checking

Checks practical use of shadow properties with interceptors.

↩ Usually asked after

More in EF Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me