如何修改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); } } } } // 这里可以添加其他实体的单独配置 }
补充说明
- 优先级:如果某个属性显式添加了
[Precision(n)]属性(比如[Precision(7)]),会覆盖这个全局默认配置,生成对应精度的DateTime2(n)列。 - 验证方式:生成迁移后,查看迁移文件中的
CreateTable或AlterColumn语句,DateTime列的类型会显示为datetime2(3)。
内容的提问来源于stack exchange,提问作者Milan Bačík
相关产品推荐
相关产品推荐

