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

📚 Interview question

Show how you would maintain audit columns such as CreatedAt, CreatedBy, ModifiedAt and ModifiedBy automatically in EF Core using a SaveChangesInterceptor and TimeProvider. What does it miss, how do you test it, and when would you use SQL Server temporal tables instead?

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.

Mid-Level Coding Intermediate auditing ef-core interceptors temporal-tables testing timeprovider

🎯 Key points

  • An IAuditable interface and a SaveChangesInterceptor that sets Created* on Added and Modified* on Modified entries
  • For entries in the Modified state, set IsModified = false on CreatedAt and CreatedBy, because Update() on a mapped DTO marks every property modified and would overwrite them
  • Use TimeProvider (in the base library since .NET 8, current in .NET 10) with GetUtcNow() so tests can use FakeTimeProvider
  • Current user from a validated principal; background jobs create a scope and supply a system identity such as system:payroll-import
  • Interceptor lifetime: scoped works with AddDbContext; with pooling the options are singleton, so the interceptor must be singleton and read the user at save time
  • ExecuteUpdate, ExecuteDelete and raw SQL bypass the interceptor; set the columns in SetProperty
  • Test the interceptor against real SQL Server with FakeTimeProvider: create, advance time, update, assert
  • Audit columns record who touched a row last; for history use temporal tables (IsTemporal() in the migration) or an audit log written in the same transaction

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"Audit columns are cross-cutting, so they belong in one place, not in every handler. I put an IAuditable interface on the entities and write a SaveChangesInterceptor. In SavingChangesAsync it loops over ChangeTracker.Entries<IAuditable>(): on Added it sets CreatedAt and CreatedBy, on Modified it sets ModifiedAt and ModifiedBy, and it sets IsModified = false on the created properties so an update that maps a whole DTO can't overwrite them. The time comes from TimeProvider, which is in the base library since .NET 8, so in tests I swap in FakeTimeProvider and assert exact timestamps.

The user comes from a scoped ICurrentUser that reads the validated principal, and background jobs set a system identity like job:invoice-run. For example, at [company] we replaced [about 40] handlers that each set ModifiedAt = DateTime.Now in 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."


Options compared

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

Lifetimes

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate centralises cross-cutting persistence logic correctly and knows the limits of audit columns.

Green flags

  • Uses an interceptor with TimeProvider and a current-user abstraction
  • Protects created fields on update
  • Knows interceptor lifetime issues with pooling
  • Names ExecuteUpdate and raw SQL as gaps, and temporal tables for history

Red flags

  • DateTime.Now in every handler
  • Claims audit columns satisfy compliance history
  • No way to test timestamps

📚 Learn in depth

1. Where the interceptor runs

SaveChangesAsync
  ├─ 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.

2. Protecting created fields

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.

3. Time

  • Use DateTimeOffset in UTC, mapped to datetimeoffset or datetime2 with UTC by convention.
  • TimeProvider.System.GetUtcNow() in production, FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing) in tests.
  • Do not use DateTime.Now: containers run in UTC, developers in AEST/AEDT, and daylight saving creates duplicate local times.

4. Who

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.

5. Temporal tables as the alternative

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.

6. What bypasses it

  • ExecuteUpdate/ExecuteDelete: set the columns in the call, e.g. .SetProperty(x => x.ModifiedAt, now).
  • ExecuteSql and stored procedures.
  • Direct database access by people or other systems.

Try it yourself

  1. Write the interceptor and a test using FakeTimeProvider that advances time between create and update.
  2. Call Update() on a detached entity with CreatedAt = default and check the generated SQL with and without IsModified = false.
  3. Switch to AddDbContextPool and see why a scoped interceptor no longer resolves.
  4. Enable a temporal table on the same entity and query TemporalAll() after three updates.

💻 Code

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);

⚠ Common mistakes

  • Mistake: Setting audit fields in each handler. Why it is wrong: Some handlers forget, and the logic drifts. Instead: One SaveChangesInterceptor.
  • Mistake: Using 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.
  • Mistake: Not protecting CreatedAt/CreatedBy on update. Why it is wrong: Update() on a mapped DTO overwrites them with defaults. Instead: Set IsModified = false on those properties.
  • Mistake: Injecting a scoped service into an interceptor used with 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.
  • Mistake: Assuming ExecuteUpdate is audited. Why it is wrong: It bypasses the change tracker and interceptors. Instead: Set the audit columns in SetProperty.
  • Mistake: Calling audit columns an audit trail. Why it is wrong: They keep only the last change. Instead: Use temporal tables or an append-only audit log for history.
  • Mistake: Storing the user's email as CreatedBy. Why it is wrong: Emails change and spread personal information. Instead: Store a stable user id.

🏛 Senior insight: trade-offs

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)

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions setting CreatedAt automatically Why: Checks the basic audit-column mechanics
    How to 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.

  2. When: Candidate mentions SaveChangesInterceptor Why: Checks interceptor types, registration and what they cannot see
    How to answer

    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.

  3. When: Candidate mentions temporal tables as the alternative Why: Checks temporal table configuration, queries and cost
    How to answer

    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.

🛠 Real-world problems: how you handle them

CreatedAt reset to 0001-01-01 on every update
Situation
[Insurance claims API on Azure SQL]. A new update endpoint mapped the request DTO onto a new entity instance and called `Update()`. Audit columns were set by a `SaveChangesInterceptor`.
Signals
A reporting dashboard showed claims "created" in year 1; a data quality check flagged [12,000] rows with `CreatedAt = 0001-01-01` and empty `CreatedBy`.
Investigation
EF Core logging showed the `UPDATE` setting every column, including `CreatedAt` and `CreatedBy`, because `Update()` marks all properties modified. The interceptor only set `ModifiedAt`/`ModifiedBy` and did not protect the created fields. Temporal history on the table gave the original values.
Resolution
Immediate: restored `CreatedAt` and `CreatedBy` from the temporal history table with a one-off `UPDATE ... FROM` using `FOR SYSTEM_TIME ALL`. Real fix: the interceptor now sets `IsModified = false` on the created properties, and the endpoint loads the entity and applies only changed fields.
Prevention
An interceptor test that updates a detached entity with default created values; a database CHECK constraint on `CreatedAt > '2000-01-01'`; a code-review checklist item against `Update()` on mapped DTOs.

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.

↩ Usually asked after

More in Production EF

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me