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.
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.
"A temporal table is a SQL Server feature, not an EF one. The table has two
datetime2period 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 theDbSet:TemporalAsOfgives me the table as it was at an instant;TemporalAllgives every version;TemporalFromTo,TemporalBetweenandTemporalContainedIngive versions active in a range with slightly different boundary rules. I read the period values withEF.Property<DateTime>(e, \"PeriodStart\"). The results are never tracked, which matters when restoring: to undelete, I queryTemporalAsOfa moment before the delete andAddthe 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 withALTERcan 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 setHISTORY_RETENTION_PERIODthrough 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."
| 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] |
| 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 |
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.
Checks whether the candidate can use temporal tables from EF Core and is honest about what they do and don't provide.
Green flags
Red flags
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.
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.
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).
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.
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).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.
TemporalAll() ordered by EF.Property<DateTime>(c, "ValidFrom").TemporalAsOf.sp_spaceused 'ContractsHistory' before and after adding a columnstore index.SYSTEM_VERSIONING = OFF.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));");
ModifiedBy, or use ledger tables when tamper evidence is required.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.TemporalAll queries. Instead: split volatile columns out, or don't version that table.HISTORY_RETENTION_PERIOD via a SQL migration step.Add to restore.GENERATED ALWAYS, so the insert or update fails. Instead: leave them as shadow properties and only read them.(Id, PeriodEnd, PeriodStart). Instead: choose by the dominant query pattern and size, and measure.temporal_type in sys.tables afterwards.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 |
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.
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].
Last updated 23 Nov 2026.