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

如何在Entity Framework中统一设置所有Decimal属性的精度?

批量设置EF中所有Decimal属性的精度为18,6

不需要逐个属性手动配置,你可以在DbContext的OnModelCreating方法中通过遍历所有实体属性的方式,自动为所有Decimal类型(包括可空Decimal)设置统一的精度和小数位,彻底解决遗漏问题。

针对EF Core的实现

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // 遍历模型中所有实体类型
    foreach (var entityType in modelBuilder.Model.GetEntityTypes())
    {
        // 筛选出当前实体中所有Decimal类型的属性
        var decimalProperties = entityType.GetProperties()
            .Where(p => p.ClrType == typeof(decimal) || p.ClrType == typeof(decimal?));

        foreach (var property in decimalProperties)
        {
            // 设置精度18,小数位6
            property.SetPrecision(18);
            property.SetScale(6);
        }
    }

    // 保留你原本的其他实体配置(如果有的话)
    // modelBuilder.Entity<Entity>().Property(...);
}

针对EF6的实现

如果使用的是旧版Entity Framework 6,写法略有不同:

using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.ModelConfiguration.Configuration;

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    foreach (var entityType in modelBuilder.Model.ConceptualModel.EntityTypes)
    {
        // 筛选Decimal类型的属性
        var decimalProperties = entityType.Properties
            .Where(p => p.TypeUsage.EdmType.Name == "Decimal");

        foreach (var property in decimalProperties)
        {
            // 重新设置精度和小数位
            property.TypeUsage = EdmTypeUsage.CreateDecimalTypeUsage(
                PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Decimal),
                precision: 18,
                scale: 6);
        }
    }

    // 其他实体配置...
}

方案优势

  • 全局配置一次性生效,后续新增的实体Decimal属性会自动应用18,6的精度,无需手动添加配置
  • 彻底避免遗漏属性导致的数据精度丢失问题,不用再花时间补配置

内容的提问来源于stack exchange,提问作者Alex Causer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:35:32