前言
EF core 6.0 开始有 build-in 的 Temporal Table 支持了.
关于 SQL Server Temporal Table 可以看这篇.
主要参考
What's New in EF Core 6.0 # SQL Server temporal tables
实战
Configuration
可以设置 History Table Name, SysStartTime, SysEndTime
默认是 TableNameHistory, PeriodStart, PeriodEnd
builder.ToTable(b => b.IsTemporal()); //builder.ToTable("Branch", b => b.IsTemporal(b => { // b.UseHistoryTable("BranchHistory"); // b.HasPeriodStart("SysStartTime"); // b.HasPeriodEnd("SysEndTime"); //}));
Create, Update, Delete
和一般操作一模一样
var branch = new Branch { Name = "Kulai1", Address = "Kulai1", ContactNumber = "07-5586349" }; _db.Branches.Add(branch); await _db.SaveChangesAsync(); await Task.Delay(3000); branch.ContactNumber = "07-2249129"; await _db.SaveChangesAsync(); await Task.Delay(3000); _db.Branches.Remove(branch); await _db.SaveChangesAsync();
Select
全部资料调出来
var branches1 = await _db.Branches.TemporalAll().ToListAsync();
调出某个时间点的资料
var branches2 = await _db.Branches.TemporalAsOf( DateTime.SpecifyKind(DateTime.Parse("2021-10-19 13:04:01.7980901"), DateTimeKind.Utc) ).ToListAsync();
注: 其实只要放进去的是 datetime 就可以了, kind 会直接被忽视掉. 它也不会智能把 Local Time 换去 UTC 哦
调出某个期间的资料
var branches4 = await _db.Branches.TemporalBetween( new DateTime(2021, 10, 19, 13, 4, 7, 284, DateTimeKind.Utc), new DateTime(2021, 10, 19, 13, 4, 7, 284, DateTimeKind.Utc) ).ToListAsync(); var branches5 = await _db.Branches.TemporalFromTo( new DateTime(2021, 10, 19, 13, 4, 7, 284, DateTimeKind.Utc), new DateTime(2021, 10, 19, 13, 4, 7, 284, DateTimeKind.Utc) ).ToListAsync();
调出某个期间内的资料
var branches6 = await _db.Branches.TemporalContainedIn( new DateTime(2021, 10, 19, 13, 4, 7, 284, DateTimeKind.Utc), new DateTime(2021, 10, 19, 13, 4, 7, 284, DateTimeKind.Utc) ).ToListAsync();