【问题标题】:DateTime.Now default value in entity configuration always sets the same DateTime in the database实体配置中的 DateTime.Now 默认值始终在数据库中设置相同的 DateTime
【发布时间】: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


    【解决方案1】:

    好的,我发现了问题。

    因为配置:

    builder.Property(x => x.EntityCreated).HasDefaultValue(DateTime.Now);
    

    当我创建迁移时,它使用的是在创建所述迁移时生成的 DateTime。因此,它将此字段的默认值设为静态 DateTime。

    为了克服这个问题,我将迁移恢复到以前,并使用了以下配置:

    builder.Property(x => x.EntityCreated).HasDefaultValueSql("getdate()");
    

    然后我创建了一个新的迁移并更新了数据库。

    这已经解决了我的问题。

    【讨论】:

      猜你喜欢
      • 2013-12-14
      • 2010-10-16
      • 1970-01-01
      • 2013-11-03
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-03
      相关资源
      最近更新 更多