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

📚 Interview question

How do you use SQL Server temporal tables with EF Core? Explain the configuration, the TemporalAsOf, TemporalAll and related query operators, using them to audit or restore data, and what they cost in storage and operations.

Covers SQL Server system-versioned temporal tables in EF Core 6+: IsTemporal configuration, period columns as shadow properties, migrations, the TemporalAsOf/All/FromTo/Between/ContainedIn operators, restoring deleted rows, what temporal tables don't record (who changed it), history growth and retention, and alternatives such as audit tables and ledger tables.

Mid-Level Theory Intermediate auditing azure-sql data-retention ef-core sql-server temporal-tables

🎯 Key points

  • System-versioned temporal table: SQL Server copies the old row version to a history table on every UPDATE/DELETE
  • EF Core 6+: ToTable(t => t.IsTemporal(...)); period columns are shadow datetime2 properties named PeriodStart/PeriodEnd by default (HasPeriodStart/HasPeriodEnd to rename) and the history table defaults to <Entity>History (UseHistoryTable)
  • Query operators: TemporalAsOf, TemporalAll, TemporalFromTo, TemporalBetween, TemporalContainedIn; results are not tracked
  • Period times are UTC and the transaction start time: pass DateTimeKind.Utc values, never local AEST/AEDT
  • Restore a deleted row: TemporalAsOf before the delete, then Add it back (or use ExecuteSql INSERT ... SELECT)
  • Records what and when, not who: add ModifiedBy or a separate audit trail
  • History grows with every update: HISTORY_RETENTION_PERIOD (via migrationBuilder.Sql); clustered columnstore on large history compresses well and suits range scans but is slower for single-row point lookups
  • Not tamper-evident (versioning can be switched off): ledger tables for that

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"A temporal table is a SQL Server feature, not an EF one. The table has two datetime2 period columns, and the engine maintains a paired history table. When a row is updated or deleted, the old version is written to history with its validity range closed at the transaction's start time, in UTC. You get every past version without writing triggers or audit code.

EF Core has supported it since version 6. I mark the entity with ToTable(t => t.IsTemporal()), optionally naming the history table and period columns. EF maps the period columns as shadow properties so they don't pollute the entity, and the migration creates the history table and turns on system versioning. For queries there are five operators on the DbSet: TemporalAsOf gives me the table as it was at an instant; TemporalAll gives every version; TemporalFromTo, TemporalBetween and TemporalContainedIn give versions active in a range with slightly different boundary rules. I read the period values with EF.Property<DateTime>(e, \"PeriodStart\"). The results are never tracked, which matters when restoring: to undelete, I query TemporalAsOf a moment before the delete and Add the entity back as a new insert.

The mistake I see is calling temporal tables an audit log. They tell you what changed and when, but not who, unless the row itself carries ModifiedBy. They're not tamper-evident either, because someone with ALTER can switch versioning off; ledger tables cover that. And the history grows with every update: a status column that changes ten times a day on a million rows adds ten million history rows a day. So I set HISTORY_RETENTION_PERIOD through a SQL migration step and put a clustered columnstore index on large history tables. Temporal tables are brilliant for 'what did this look like last Tuesday', and expensive if you version a hot table you never query."


Query operators

Operator Returns
TemporalAsOf(t) One row per entity: the version valid at t
TemporalAll() Every version, current and history
TemporalFromTo(a, b) Versions active any time in [a, b) (excludes those starting at b)
TemporalBetween(a, b) Like FromTo but includes versions starting at b
TemporalContainedIn(a, b) Versions that started and ended within [a, b]

Temporal tables vs alternatives

Approach Who What/when Tamper-evident Effort
Temporal tables Only via a column Yes, full row versions No Low
Audit table via SaveChangesInterceptor Yes Changed columns, your format No Medium; misses ExecuteUpdate and raw SQL
Ledger tables (SQL Server 2022 / Azure SQL) Via a column Yes Yes (cryptographic digests) Medium; updatable ledger tables have restrictions
Change Data Capture No Yes, for downstream systems No Operational overhead

Production example

Versioning a [customer contract] table let support answer 'what were the terms on 3 March' in one query instead of a [two-day] restore request; with a [7-year] retention policy and columnstore history, [40M] history rows used [~6 GB] instead of [~38 GB] as rowstore.

🔍 What the interviewer is checking

Checks whether the candidate can use temporal tables from EF Core and is honest about what they do and don't provide.

Green flags

  • Knows the configuration and the query operators, and that results are untracked.
  • Mentions UTC period times and restoring deleted rows.
  • Raises storage growth and retention.
  • Distinguishes temporal history from audit (who) and ledger (tamper evidence).

Red flags

  • Thinks EF Core implements the history itself.
  • Calls temporal tables a complete audit solution.
  • Ignores history size.

📚 Learn in depth

1. How SQL Server maintains history

UPDATE Contracts SET Rate = 9.5 WHERE Id = 7     (transaction starts at T2)

Contracts (current)                        ContractsHistory
Id Rate PeriodStart PeriodEnd               Id Rate PeriodStart PeriodEnd
7  9.5  T2          9999-12-31              7  8.0  T1          T2

DELETE moves the row to history with PeriodEnd = transaction start. The period columns are GENERATED ALWAYS AS ROW START/END, so applications can't write them. All rows changed in one transaction share the same timestamp.

2. EF Core configuration and migration

modelBuilder.Entity<Contract>().ToTable("Contracts", t => t.IsTemporal(h =>
{
    h.HasPeriodStart("ValidFrom");
    h.HasPeriodEnd("ValidTo");
    h.UseHistoryTable("ContractsHistory");
}));

The migration creates the table with PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo) and WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.ContractsHistory)). Later schema changes (adding a column) are handled by EF Core, which temporarily turns versioning off, alters both tables and turns it back on; review those migrations carefully because the window briefly stops recording history.

3. What the operators generate

var asAt = await db.Contracts.TemporalAsOf(new DateTime(2026, 3, 3, 0, 0, 0, DateTimeKind.Utc))
    .Where(c => c.CustomerId == id).ToListAsync(ct);
SELECT [c].[Id], [c].[CustomerId], [c].[Rate], [c].[ValidFrom], [c].[ValidTo]
FROM [Contracts] FOR SYSTEM_TIME AS OF '2026-03-03T00:00:00.0000000' AS [c]
WHERE [c].[CustomerId] = @__id_0

The query reads both tables (a UNION inside the engine). Times are UTC: pass DateTimeKind.Utc values or convert from Australian local time first (AEST/AEDT).

4. Restoring

var old = await db.Contracts.TemporalAsOf(deletedAtUtc.AddTicks(-1)).SingleAsync(c => c.Id == id, ct);
db.Contracts.Add(old);      // untracked result -> Added -> INSERT; identity keys need IDENTITY_INSERT or a new key
await db.SaveChangesAsync(ct);

With identity keys, re-inserting the same key needs SET IDENTITY_INSERT; GUID or sequence keys make restores simpler.

5. Storage and retention

  • History size ~ rows x updates per row x row size. Hot columns on big tables dominate.
  • ALTER TABLE Contracts SET (SYSTEM_VERSIONING = ON (HISTORY_RETENTION_PERIOD = 7 YEARS)); in migrationBuilder.Sql; a background task deletes aged history. The database option TEMPORAL_HISTORY_RETENTION must be on (it is by default on Azure SQL).
  • A clustered columnstore index on the history table compresses it heavily and suits range scans.
  • Consider splitting volatile columns (last-seen timestamps) out of the versioned table.

6. Compliance angle

The Privacy Act's APP 11.2 expects personal information to be destroyed or de-identified when no longer needed. History tables keep copies of every old value, including corrected personal details, so retention and erasure processes must cover them too.

Try it yourself

  1. Make an entity temporal, update a row three times and query TemporalAll() ordered by EF.Property<DateTime>(c, "ValidFrom").
  2. Delete a row and restore it with TemporalAsOf.
  3. Run the same update inside one transaction twice and confirm both versions share a timestamp.
  4. Measure history size with sp_spaceused 'ContractsHistory' before and after adding a columnstore index.
  5. Add a column in a migration and read the generated SQL around SYSTEM_VERSIONING = OFF.

💻 Code

Configure, query and restore with a temporal entity.

namespace Contracts.Data;

using Microsoft.EntityFrameworkCore;

public sealed class Contract
{
    public Guid Id { get; init; } = Guid.CreateVersion7(); // client key: restores don't need IDENTITY_INSERT
    public Guid CustomerId { get; init; }
    public decimal Rate { get; set; }
    public string ModifiedBy { get; set; } = "";            // temporal tables don't record who
}

public sealed class ContractsDbContext(DbContextOptions<ContractsDbContext> o) : DbContext(o)
{
    public DbSet<Contract> Contracts => Set<Contract>();

    protected override void OnModelCreating(ModelBuilder b) =>
        b.Entity<Contract>().ToTable("Contracts", t => t.IsTemporal(h =>
        {
            h.HasPeriodStart("ValidFrom");
            h.HasPeriodEnd("ValidTo");
            h.UseHistoryTable("ContractsHistory");
        }));
}

public sealed record ContractVersion(decimal Rate, string ModifiedBy, DateTime ValidFrom, DateTime ValidTo);

public sealed class ContractHistory(ContractsDbContext db)
{
    public Task<List<ContractVersion>> VersionsAsync(Guid id, CancellationToken ct) =>
        db.Contracts.TemporalAll()
          .Where(c => c.Id == id)
          .OrderBy(c => EF.Property<DateTime>(c, "ValidFrom"))
          .Select(c => new ContractVersion(c.Rate, c.ModifiedBy,
               EF.Property<DateTime>(c, "ValidFrom"), EF.Property<DateTime>(c, "ValidTo")))
          .ToListAsync(ct);

    public async Task RestoreAsync(Guid id, DateTime deletedAtUtc, string user, CancellationToken ct)
    {
        var old = await db.Contracts.TemporalAsOf(deletedAtUtc.AddTicks(-1)).SingleAsync(c => c.Id == id, ct);
        old.ModifiedBy = user;
        db.Contracts.Add(old);          // temporal results are untracked, so this is an INSERT
        await db.SaveChangesAsync(ct);
    }
}
// In a migration: add retention (EF Core has no API for it).
migrationBuilder.Sql("ALTER TABLE dbo.Contracts SET (SYSTEM_VERSIONING = ON (HISTORY_RETENTION_PERIOD = 7 YEARS));");

⚠ Common mistakes

  • Mistake: Calling temporal tables an audit log. Why it is wrong: they record what and when, not who, and aren't tamper-evident. Instead: add ModifiedBy, or use ledger tables when tamper evidence is required.
  • Mistake: Passing local Australian times, or DateTime values with DateTimeKind.Local/Unspecified, to TemporalAsOf or TemporalFromTo. Why it is wrong: period columns are UTC, so results are off by 10-11 hours and a restore can pick the wrong version. Instead: convert with TimeZoneInfo.ConvertTimeToUtc or use DateTimeOffset.UtcDateTime, and pass DateTimeKind.Utc values only.
  • Mistake: Versioning a hot table with frequently changing columns. Why it is wrong: history grows by millions of rows a day and slows TemporalAll queries. Instead: split volatile columns out, or don't version that table.
  • Mistake: No retention policy. Why it is wrong: history grows forever and keeps personal data past its required life (APP 11.2). Instead: HISTORY_RETENTION_PERIOD via a SQL migration step.
  • Mistake: Trying to update an entity returned by a temporal query. Why it is wrong: results are untracked, so changes aren't saved. Instead: load the current row normally, or Add to restore.
  • Mistake: Writing to period columns from the application. Why it is wrong: they're GENERATED ALWAYS, so the insert or update fails. Instead: leave them as shadow properties and only read them.
  • Mistake: Putting a columnstore index on every history table by reflex. Why it is wrong: it is excellent for large range scans and storage, but single-entity 'show me this row's versions' lookups can get slower than with a rowstore index on (Id, PeriodEnd, PeriodStart). Instead: choose by the dominant query pattern and size, and measure.
  • Mistake: Applying schema-change migrations without reviewing them. Why it is wrong: EF turns versioning off briefly, and a failed migration can leave it off. Instead: review and test the migration, and check temporal_type in sys.tables afterwards.

🏛 Senior insight: trade-offs

Temporal tables are the cheapest way to answer 'what did this look like then' and to undo mistakes, but I'm selective about which tables get them: reference and contract-type data with modest update rates are ideal; high-churn operational tables usually aren't. I estimate history growth before turning it on (rows x daily updates x row size) and add retention in the same migration.

For compliance conversations I'm precise: temporal history isn't an audit trail of actors and isn't tamper-proof. If the requirement is 'prove nobody altered this record', that's ledger tables; if it's 'who changed what', that's an audit table or event log with user identity, which temporal history complements rather than replaces.

Option When it fits Cost When not to
Temporal table Point-in-time queries, undelete, low-to-medium churn History storage, migration care Hot tables, 'who' audits
Interceptor audit table Who changed which columns Code, misses bulk paths Full row history needs
Ledger table Tamper evidence for regulators Restrictions on schema changes Ordinary history
Event sourcing History is the domain model Big architectural shift Bolt-on auditing

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions auditing with temporal tables. Why: Checks recording who changed a row, which temporal tables don't.
    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 compares temporal tables with an audit interceptor. Why: Checks the interceptor-based alternative for audit trails.
    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.

🛠 Real-world problems: how you handle them

Temporal history table growing 40 GB a month on Azure SQL
Situation
A [fleet-tracking] system on Azure SQL (General Purpose, Australia Southeast) versioned its `Vehicles` table to see past assignments. `Vehicles` also held `LastSeenAt`, updated every [30 seconds] for [~20k] vehicles.
Signals
Storage alerts at 80% of the max size; `sp_spaceused` showed `VehiclesHistory` at [~180 GB]; `TemporalAll` reports timing out; the cost report showed a jump in storage tier.
Investigation
Queried history counts by day (`SELECT CAST(ValidTo AS date), COUNT(*) ...`) and found [~57M] rows a day; compared consecutive versions and saw only `LastSeenAt` changed in [99%] of them. Checked `sys.tables.history_retention_period`: not set.
Resolution
Immediately: set `HISTORY_RETENTION_PERIOD = 90 DAYS` after confirming with the business that assignment history older than that wasn't needed, and let the cleanup task run. Then: moved `LastSeenAt` into a separate non-temporal `VehicleTelemetry` table (expand/contract migration), added a clustered columnstore index on the history table, and re-tested the reports.
Prevention
A design checklist item: estimate history growth before enabling temporal; retention set in the same migration; a storage-growth alert on history tables; an ADR on which tables are versioned.

How to tell it (STAR)

**S:** At [company], our [fleet-tracking] database on Azure SQL was heading for its size limit, and the history table behind one temporal table was [180 GB]. **T:** I had to stop the growth without losing the assignment history the business relied on. **A:** I found that [99%] of the history rows came from a last-seen timestamp updated every [30 seconds], which meant every heartbeat created a new version. I agreed a [90-day] retention period with the business, moved the heartbeat column into its own non-temporal table with a two-step migration, and put a columnstore index on the history. **R:** History dropped to [~4 GB], growth went from [40 GB] to [under 1 GB] a month, and the reports ran in [seconds instead of timing out].

↩ Usually asked after

More in Advanced EF Core

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me