Knowing only the current state of production data is often not enough. When did a product price change? Which value existed before an incorrect update? What did a deleted customer record look like before it disappeared? Application logs may not answer these questions reliably, and manually maintained audit tables are easy to implement inconsistently.
SQL Server temporal tables automatically preserve previous row versions at the database level. EF Core supports creating temporal tables through migrations, querying historical versions, and reading data as it existed at a specific UTC timestamp. This article uses a product-price correction scenario to explain the design and its operational limits.
The problem temporal tables solve
Assume a Products table containing a product name, price, and active flag. An administrator accidentally changes a price from 249.90 to 2,499.00. A few minutes later, another operation deletes the product. In a conventional table, the current database may contain no evidence of the previous values unless the application explicitly recorded them.
A system-versioned temporal table maintains a current table and a related history table. When a row is updated, SQL Server stores the previous version in the history table. When a row is deleted, the last version is preserved as well. Each version has a validity start and end time. The application can continue using ordinary INSERT, UPDATE, and DELETE operations while SQL Server manages the history.
Configuring the EF Core model
The following entity maps the period columns to CLR properties. This is optional because EF Core can also map them as shadow properties, but explicit properties make diagnostic and reporting code easier to read.
public sealed class Product
{
public int Id { get; set; }
public string Name { get; set; } = null!;
public decimal Price { get; set; }
public bool IsActive { get; set; }
public DateTime ValidFrom { get; private set; }
public DateTime ValidTo { get; private set; }
}Configure the entity as a temporal table:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.ToTable("Products", table => table.IsTemporal(temporal =>
{
temporal.HasPeriodStart(p => p.ValidFrom);
temporal.HasPeriodEnd(p => p.ValidTo);
temporal.UseHistoryTable("ProductHistory");
}));
}SQL Server generates and maintains the period values. Application code should not assign them manually. The timestamps are generated in UTC, which is important when the application runs across multiple servers or time zones.
Creating the schema with migrations
For a new table, create and apply a migration:
dotnet ef migrations add AddTemporalProducts
dotnet ef database updateThe resulting schema contains the current table, two period columns, a primary key, and the associated ProductHistory table. A system-versioned temporal table requires a primary key and exactly two non-nullable datetime2 period columns.
Converting an existing table requires more planning. Adding period columns, creating the history table, and building indexes can affect locks, disk usage, and deployment time. Test the migration against a production-sized copy before applying it during a busy maintenance window.
Normal writes continue to work
Application code can read and update the current row normally:
var product = await db.Products
.SingleAsync(p => p.Id == productId, cancellationToken);
product.Price = 249.90m;
await db.SaveChangesAsync(cancellationToken);Before the update becomes current, the previous row version is written to the history table. The same behavior applies to deletes. However, a temporal table is not automatically a complete user audit log. It does not identify which user made the change, which IP address was used, or why the operation was approved. Those facts require a separate audit design or an application-level correlation mechanism.
Reading a row at a point in time
To inspect the product immediately before the incorrect update, use TemporalAsOf. The timestamp should be UTC:
var pointInTime = new DateTime(2026, 11, 17, 10, 30, 0, DateTimeKind.Utc);
var oldProduct = await db.Products
.TemporalAsOf(pointInTime)
.AsNoTracking()
.SingleOrDefaultAsync(p => p.Id == productId, cancellationToken);This query returns the version that was valid at the specified instant. It can also return a row that has since been deleted, provided that the row existed at that point in time. Finding a historical version and blindly writing it back to the current table are different operations; restoration should be deliberate and validated.
Correcting an incorrect price
After identifying the historical version, copy only the fields that should be restored. This avoids overwriting newer business changes that are unrelated to the incident:
var current = await db.Products
.SingleAsync(p => p.Id == productId, cancellationToken);
var historical = await db.Products
.TemporalAsOf(pointInTime)
.AsNoTracking()
.SingleOrDefaultAsync(p => p.Id == productId, cancellationToken);
if (historical is null)
throw new InvalidOperationException("The product did not exist at that time.");
current.Price = historical.Price;
current.IsActive = historical.IsActive;
await db.SaveChangesAsync(cancellationToken);This correction creates a new temporal version. That is desirable because the history now shows both the original mistake and the later correction. A restoration process should normally require authorization, record an incident or ticket identifier, and validate whether newer changes must be preserved.
Inspecting every version
Use TemporalAll to list all versions of a row:
var history = await db.Products
.TemporalAll()
.Where(p => p.Id == productId)
.OrderBy(p => p.ValidFrom)
.Select(p => new
{
p.Id,
p.Name,
p.Price,
p.IsActive,
p.ValidFrom,
p.ValidTo
})
.AsNoTracking()
.ToListAsync(cancellationToken);The current row usually has a ValidTo value representing the maximum datetime2 value. Historical rows have an end time corresponding to the next version. These are database transaction times, not necessarily business event times. If data is imported hours after an event occurred, the temporal interval reflects the database transaction rather than the original business timestamp.
Production considerations
- History grows continuously: Frequently updated tables can generate many historical rows. Define retention, archival, and storage monitoring policies.
- Plan indexes: Rowstore indexes are useful for point lookups and single-record audit screens. Large analytical workloads may require different history-table storage and indexing strategies.
- Protect sensitive history: Old personal, financial, or confidential values remain in the history table. Apply authorization, encryption, backup, and retention policies to both current and history data.
- Measure migration impact: Test conversion time, blocking, transaction-log growth, and disk consumption with production-sized data.
- Do not treat temporal history as immutable evidence: A sufficiently privileged database operator can disable system versioning and modify the history table. Strong audit requirements may need additional controls, restricted permissions, and external or append-only logging.
Conclusion
EF Core and SQL Server temporal tables preserve row history without requiring every application update path to manually insert audit records. They are particularly useful for prices, contracts, inventory, customer data, and configuration records where teams need to answer “what was true at that time?” and recover from incorrect changes in a controlled way.
Temporal tables do not automatically capture the acting user, business reason, approval, or request context. A robust design uses temporal history for database-managed row versions and complements it with an application audit strategy when accountability and business traceability are required.
Sources
- https://learn.microsoft.com/en-us/ef/core/providers/sql-server/temporal-tables
- https://learn.microsoft.com/en-us/sql/relational-databases/tables/temporal-tables?view=sql-server-ver17
- https://learn.microsoft.com/en-us/sql/relational-databases/tables/temporal-table-considerations-and-limitations?view=sql-server-ver15
0 Comments