Skip to content

Instantly share code, notes, and snippets.

@icalvo
Created April 24, 2026 07:27
Show Gist options
  • Select an option

  • Save icalvo/a9b33fb148f984f60a0cc9febc70f59e to your computer and use it in GitHub Desktop.

Select an option

Save icalvo/a9b33fb148f984f60a0cc9febc70f59e to your computer and use it in GitHub Desktop.
Helpers for using EF with SQL Server Temporal Tables
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public static class TemporalHelpers
{
public const string PeriodStartFieldName = "PeriodStart";
public const string PeriodEndFieldName = "PeriodEnd";
extension<T>(TableBuilder<T> tableBuilder) where T : class
{
/// <summary>
/// Configures the table to be temporal with project defaults.
/// </summary>
/// <returns></returns>
public TableBuilder<T> UseHistoryTable() =>
tableBuilder.IsTemporal(t =>
{
t.HasPeriodStart(PeriodStartFieldName);
t.HasPeriodEnd(PeriodEndFieldName);
t.UseHistoryTable($"{tableBuilder.Name}History");
});
}
extension<T>(IQueryable<T> queryable)
{
/// <summary>
/// Maps to a Period<T> object that contains the entity and the period start and end dates.
/// </summary>
/// <returns></returns>
public IQueryable<Period<T>> AsPeriods()
{
return queryable.Select(e => new Period<T>(
e,
EF.Property<DateTime>(e!, PeriodStartFieldName),
EF.Property<DateTime>(e!, PeriodEndFieldName)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment