SQL Server temporal tables support for Entity Framework Core
The Intent.EntityFrameworkCore.TemporalTables module adds SQL Server temporal tables support to Entity Framework Core, enabling automatic history tracking for entities.
// Returns only current customersvar customers = await _repository.FindAllAsync();// Standard filteringvar customer = await _repository.FindByIdAsync(customerId);
// Get customer as they were on January 1, 2024var customerAtPoint = await _dbContext.Customers .TemporalAsOf(new DateTime(2024, 1, 1)) .FirstOrDefaultAsync(x => x.Id == customerId);
// Get all versions between two datesvar customerVersions = await _dbContext.Customers .TemporalBetween( new DateTime(2024, 1, 1), new DateTime(2024, 12, 31)) .Where(x => x.Id == customerId) .ToListAsync();
// Get all versions since a specific datevar recentChanges = await _dbContext.Customers .TemporalFromTo( new DateTime(2024, 1, 1), DateTime.UtcNow) .Where(x => x.Id == customerId) .ToListAsync();
// Get versions that existed entirely within a periodvar containedVersions = await _dbContext.Customers .TemporalContainedIn( new DateTime(2024, 1, 1), new DateTime(2024, 12, 31)) .Where(x => x.Id == customerId) .ToListAsync();
public async Task RestoreCustomerToDateAsync(Guid customerId, DateTime restoreDate){ // Get the version at the restore point var historicalVersion = await _dbContext.Customers .TemporalAsOf(restoreDate) .FirstOrDefaultAsync(x => x.Id == customerId); if (historicalVersion == null) { throw new InvalidOperationException("No version found at that date"); } // Get current version var currentVersion = await _dbContext.Customers .FindAsync(customerId); if (currentVersion != null) { // Restore properties currentVersion.Name = historicalVersion.Name; currentVersion.Email = historicalVersion.Email; // ... restore other properties await _dbContext.SaveChangesAsync(); }}
CREATE TABLE Customers( Id uniqueidentifier NOT NULL PRIMARY KEY, Name nvarchar(200) NOT NULL, Email nvarchar(256) NOT NULL, ValidFrom datetime2 GENERATED ALWAYS AS ROW START NOT NULL, ValidTo datetime2 GENERATED ALWAYS AS ROW END NOT NULL, PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo))WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.CustomerHistory));
CREATE TABLE CustomerHistory( Id uniqueidentifier NOT NULL, Name nvarchar(200) NOT NULL, Email nvarchar(256) NOT NULL, ValidFrom datetime2 NOT NULL, ValidTo datetime2 NOT NULL);