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

EF7中如何为JSON列中的值设置小数精度?

问题描述

我有一个包含JSON列的表,示例模型如下:

public class TableA
{
    public int Id {get;set;}
    public List<Item> Items {get;set;} = new List<Item>();
}

public class Item
{
    public string ItemName {get;set;}
    public double ItemValue {get;set;}
}

使用Fluent API配置该关系的代码如下:

internal sealed class TableAConfiguration: IEntityTypeConfiguration<TableA>
{
    public void Configure(EntityTypeBuilder<TableA> builder)
    {           
        ...

        builder.OwnsMany(o => o.Items,
            ms => { ms.ToJson(); });
    }
}

生成迁移并更新数据库后,出现如下警告信息:

No store type was specified for the decimal property 'ItemValue' on
entity type 'Item'. This will cause
values to be silently truncated if they do not fit in the default
precision and scale. Explicitly specify the SQL server column type
that can accommodate all the values in 'OnModelCreating' using
'HasColumnType', specify precision and scale using 'HasPrecision', or
configure a value converter using 'HasConversion'.

但无法通过IEntityTypeConfiguration指定精度,请问还有其他设置精度的方法吗?

解决方案

可以直接在OwnsMany的配置委托里对嵌套的Item属性设置精度,无需额外的IEntityTypeConfiguration,具体有两种实现方式:

方式一:直接配置属性精度

修改TableAConfiguration代码,在ms.ToJson()之后,通过ms.Property()指定ItemValue的精度和小数位数:

internal sealed class TableAConfiguration: IEntityTypeConfiguration<TableA>
{
    public void Configure(EntityTypeBuilder<TableA> builder)
    {           
        // 其他配置...

        builder.OwnsMany(o => o.Items, ms => 
        {
            ms.ToJson();
            // 示例:设置精度18,小数位2,可根据实际需求调整
            ms.Property(i => i.ItemValue).HasPrecision(18, 2);
        });
    }
}

方式二:通过值转换器指定存储类型

如果需要自定义存储格式,可结合HasConversion和HasColumnType配置:

internal sealed class TableAConfiguration: IEntityTypeConfiguration<TableA>
{
    public void Configure(EntityTypeBuilder<TableA> builder)
    {           
        // 其他配置...

        builder.OwnsMany(o => o.Items, ms => 
        {
            ms.ToJson();
            ms.Property(i => i.ItemValue)
               .HasConversion<double>()
               .HasColumnType("decimal(18,2)");
        });
    }
}

另外注意:模型中ItemValue是double类型,但警告提及的是decimal属性,建议确认类型一致性,避免不必要的转换问题。

内容的提问来源于stack exchange,提问作者1gn1ter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 10:54:59