数值不适合 System.Decimal

Numeric value does not fit in a System.Decimal

我正在使用带有 Entity Framework 的 Postgres 数据库。

在我的数据库中有一个 table,它有 price (numeric) 列和 12314.0464314894136514658489431486146548

这样的值

当我使用 LINQ 查询获取数据时,它抛出错误:

An exception of type 'System.OverflowException' occurred in mscorlib.dll but was not handled in user code

Additional information: Numeric value does not fit in a System.Decimal

在我的模型 class 中 price 属性 的数据类型为 decimal(19,4)

我认为来自数据库 table 的值精度更高,而我的模型 属性 精度较低,

所以我的问题是:有没有什么方法可以从数据库 table 中获取具有 truncated/rounded 值的数据,这将适合我的模型 属性?

注意:我被限制不能对数据库进行任何更改,所有我必须在我的 C# 代码中做的事情。

提前致谢

如果您收到文本形式的值并且您需要四位小数,您可以像这样转换:

decimal d = 0;
d = Convert.ToDecimal(Math.Round(Convert.ToDouble("12314.0464314894136514658489431486146548"), 4));

// d -> 12314.0464

您可以在数据库级别四舍五入价格字段值。试试这个

var myRecords = model.Database
.SqlQuery<MyRecord>("select ..., cast(Price as numeric(19,4)) from mytable");

.edmx文件中添加Select查询,解决我的精度问题。

导航到 <EntitySet> 标签,并添加 select 查询。

<edmx:StorageModels>
    <Schema>
        <EntityContainer>
            <EntitySet Name="books" EntityType="Self.books" store:Type="Tables" store:Schema="public">
                <DefiningQuery>SELECT "books"."name", (("books"."price")::double precision)::numeric FROM "public"."books" AS "books"</DefiningQuery>
            </EntitySet>
        </EntityContainer>
    </Schema>
</edmx:StorageModels>

现在,当我 select 该列时,使用下面的查询,它 returns 将正确适合 c# 的十进制数据类型的值,无需在数据库中进行任何更改。

var result = context.books.Where(x => x.name == "My Book").ToList();

试试这个:

select round(price,4) from books