【发布时间】:2021-04-19 07:49:11
【问题描述】:
我在使用 EF Core 在 Fluent API 中配置我的实体时遇到了一个奇怪的问题。
我的所有实体都有一个 EntityCreated 字段,它是一个 DateTime 对象,在作为新记录添加到数据库时设置为当前 DateTime。
以下是我设置这个默认值的配置代码:
builder.Property(x => x.EntityCreated).HasDefaultValue(DateTime.Now);
问题是每次添加新记录时,它不会使用当前的DateTime,而是使用在db中创建第一条记录时使用的第一个DateTime。
我很困惑,因为我在提交到数据库之前检查了这个 DateTime 是否没有在其他任何地方设置,我不确定其他人是否有同样的问题,但我有点摸不着头脑对此,我还尝试了其他一些方法,例如:
1) builder.Property(x => x.EntityCreated).HasDefaultValueSql("getdate()");
2) builder.Property(x => x.EntityCreated).HasComputedColumnSql("getdate()");
谁能帮助解决这个问题?
非常感谢。
【问题讨论】:
标签: entity-framework-core ef-fluent-api