Azh*_*ari 1 entity-framework-core ef-fluent-api
在使用 EF Core 在 Fluent API 中配置我的实体时,我遇到了一个奇怪的问题。
我所有的实体都有一个EntityCreated字段,它是一个 DateTime 对象,该字段在作为新记录添加到数据库时设置为当前 DateTime。
以下是我设置此默认值的配置代码:
builder.Property(x => x.EntityCreated).HasDefaultValue(DateTime.Now);
Run Code Online (Sandbox Code Playgroud)
问题是每次添加新记录时,它不会使用当前的 DateTime,而是使用它在 db 中创建第一条记录时使用的第一个 DateTime。
我很困惑,因为我已经检查过这个 DateTime 在提交到数据库之前没有被设置在其他任何地方,我不确定是否有人有同样的问题,但我有点摸不着头脑。我还尝试了其他一些方法,例如:
1) builder.Property(x => x.EntityCreated).HasDefaultValueSql("getdate()");
2) builder.Property(x => x.EntityCreated).HasComputedColumnSql("getdate()");
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助解决这个问题吗?
非常感激。
好的,我想出了这个问题。
因为配置:
builder.Property(x => x.EntityCreated).HasDefaultValue(DateTime.Now);
Run Code Online (Sandbox Code Playgroud)
当我创建迁移时,它使用的是在创建所述迁移时生成的 DateTime。因此,它将此字段的默认值设为静态 DateTime。
为了克服这个问题,我将迁移恢复到以前的状态,并使用了以下配置:
builder.Property(x => x.EntityCreated).HasDefaultValueSql("getdate()");
Run Code Online (Sandbox Code Playgroud)
然后我创建了一个新的迁移并更新了数据库。
这现在已经解决了我的问题。
| 归档时间: |
|
| 查看次数: |
2591 次 |
| 最近记录: |