You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Entity Framework Core中DateTime2的默认生成精度?

修改EF Core Code First默认SQL Server DateTime列类型为DateTime2(3)

要实现未显式指定[Precision]属性时默认生成DateTime2(3)类型列,你可以在DbContext的OnModelCreating方法中全局配置所有DateTime属性的默认精度:

  • 遍历所有实体的DateTime(包括可空DateTime?)属性
  • 对没有显式设置精度的属性,统一设置精度为3

具体代码如下:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var property in entityType.GetProperties())
        {
            // 匹配DateTime和可空DateTime类型
            if (property.ClrType == typeof(DateTime) || property.ClrType == typeof(DateTime?))
            {
                // 仅对未显式设置精度的属性生效
                if (!property.GetPrecision().HasValue)
                {
                    property.SetPrecision(3);
                }
            }
        }
    }

    // 这里可以添加其他实体的单独配置
}

补充说明

  1. 优先级:如果某个属性显式添加了[Precision(n)]属性(比如[Precision(7)]),会覆盖这个全局默认配置,生成对应精度的DateTime2(n)列。
  2. 验证方式:生成迁移后,查看迁移文件中的CreateTable或AlterColumn语句,DateTime列的类型会显示为datetime2(3)。

内容的提问来源于stack exchange,提问作者Milan Bačík

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 07:30:52