Created
April 24, 2026 07:27
-
-
Save icalvo/a9b33fb148f984f60a0cc9febc70f59e to your computer and use it in GitHub Desktop.
Helpers for using EF with SQL Server Temporal Tables
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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