【发布时间】:2022-01-15 02:40:30
【问题描述】:
我们最近将项目升级到Microsoft.EntityFrameworkCore 6.0.0。此版本支持开箱即用的 SQL Server 时态表。
https://stackoverflow.com/a/70017768/3850405
自 Entity Framework Core 3.1 以来,我们一直使用时态表,使用此处描述的自定义迁移:
https://stackoverflow.com/a/64776658/3850405
https://stackoverflow.com/a/64244548/3850405
仅仅遵循微软的指南当然行不通,因为默认列名是PeriodStart 和PeriodEnd,而不是我们的SysStartTime 和SysEndTime。历史表名也不匹配。
modelBuilder
.Entity<Comment>()
.ToTable("Comments", b => b.IsTemporal());
已创建迁移:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterTable(
name: "Comments")
.Annotation("SqlServer:IsTemporal", true)
.Annotation("SqlServer:TemporalHistoryTableName", "CommentsHistory")
.Annotation("SqlServer:TemporalHistoryTableSchema", null)
.Annotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd")
.Annotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart");
migrationBuilder.AddColumn<DateTime>(
name: "PeriodEnd",
table: "Comments",
type: "datetime2",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified))
.Annotation("SqlServer:IsTemporal", true)
.Annotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd")
.Annotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart");
migrationBuilder.AddColumn<DateTime>(
name: "PeriodStart",
table: "Comments",
type: "datetime2",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified))
.Annotation("SqlServer:IsTemporal", true)
.Annotation("SqlServer:TemporalPeriodEndColumnName", "PeriodEnd")
.Annotation("SqlServer:TemporalPeriodStartColumnName", "PeriodStart");
}
创建自定义转换应按如下所述解决此问题:
modelBuilder
.Entity<Comment>()
.ToTable("Comments", tb => tb.IsTemporal(temp =>
{
temp.UseHistoryTable("Comments", "History");
temp.HasPeriodStart("SysStartTime");
temp.HasPeriodEnd("SysEndTime");
}));
但是,当我这样做时,Add-Migration 命令出现以下错误:
期间属性“Comment.SysStartTime”必须是影子属性。
为了验证我恢复到的任何其他代码没有问题:
modelBuilder
.Entity<Comment>()
.ToTable("Comments", b => b.IsTemporal());
然后将public DateTime PeriodStart { get; set; }添加到Comment。
然后我收到了错误:
期间属性“Comment.PeriodStart”必须是影子属性。
有没有办法解决这个问题?我们使用我们的SysStartTime 作为最后修改/最后更新的值,它工作得非常好。必须通过EF.Property<DateTime>(comment, "SysStartTime")) 包含它似乎非常不必要,因为该列同时存在于临时表和原始表中。
【问题讨论】:
标签: c# .net entity-framework entity-framework-core temporal-tables