System-Versioned Tables in SQL Server/EF Core

Published July 13, 2024SQL ServerTemporal TablesBlazor

I have been playing around with Blazor Server for a while now, today I wanted to build a simple catalog website

Since SQL Server 2016, we have had the ability to create temporal tables. Temporal tables are a type of table that keep a history of the data. This is useful for auditing purposes, as well as for querying the data as it was at a specific point in time. In SQL Server, temporal tables are implemented using system-versioned tables.

EF Core has a great support for temporal tables, you just need to add the IsTemporal method to the Entity<T> method. Given the following Product entity:

using System.ComponentModel.DataAnnotations.Schema;

public record Product
{
    public int Id { get; init; }
    public string Name { get; init; }
    public string Description { get; init; }
    public decimal Price { get; init; }
    public string ImageUrl { get; init; }
    
    [NotMapped]
    public DateTime ValidFrom { get; set; }
    [NotMapped]
    public DateTime ValidTo { get; set; }
}

In the OnModelCreating method of the DbContext, you can add the IsTemporal method to the Entity<T> method:

using Microsoft.EntityFrameworkCore;

public class EshopDbContext(DbContextOptions<EshopDbContext> options) : DbContext(options)
{
    public DbSet<Product> Products { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Product>().ToTable(tb => tb.IsTemporal())
            .Property(i => i.Price)
            .HasColumnType("money");
    }
}