实体框架十进制舍入在投影中不一致

时间:2015-12-23 02:14:04

标签: c# entity-framework decimal rounding

在将十进制值乘以和添加整数列时,EF6处理舍入的方式似乎不一致。

// CREATE TABLE MyTable (MyIntValue INT NOT NULL)
// INSERT INTO MyTable (MyIntValue) VALUES (10)
const int IntScale = 5;
const decimal DecimalScale = 5;
const decimal DecimalScale2 = 5.0m;
context.Set<MyTable>()
    .Select(row => new
    {
         WithFloats = 0.5f + (row.MyIntValue * 5.0f),                         // 50.5
         WithDecimals = 0.5m + (row.MyIntValue * 5.0m),                       // 51 
         WithDecimals2 = 0.5m + ((decimal)row.MyIntValue * 5.0m),             // 50.5            
         WithDecimals3 = 0.5m + ((decimal)row.MyIntValue * IntScale),         // 51
         WithDecimals4 = 0.5m + ((decimal)row.MyIntValue * (decimal)IntScale) // 51
         WithDecimals5 = 0.5m + ((decimal)row.MyIntValue * DecimalScale)      // 51
         WithDecimals6 = 0.5m + ((decimal)row.MyIntValue * DecimalScale2)     // 50.5
    })
    .Single();

当然这不是预期/正确的行为吗?我希望WithDecimals值为50.5(而不是51)。我忽略了简单的事情吗?如何在不更改其他常量类型的情况下确保WithoutDecimals不会被舍入?

为WithFloats和WithDecimals(分别)生成的SQL:

,CAST(0.5 AS REAL) + (CAST(MyIntValue AS REAL) * CAST(5 AS REAL)) AS WithFloats
,0.5 + (CAST(MyIntValue AS DECIMAL(19,0)) * CAST(5 AS DECIMAL(18))) AS WithDecimals

1 个答案:

答案 0 :(得分:0)

使用数据注释明确定义列类型,以及十进制字段的精度和比例

[Column(TypeName = "decimal(5,2)")]
public decimal MyDecimal { get; set; }

您可以找到默认的LINQ-to-SQL CLR类型映射,这在使用EF here时适用。

阅读T-SQL数字和十进制数据类型here