[英]Entity Framework decimal rounding inconsistent in projection
EF6 appears to be inconsistent in how it handles rounding when multiplying and adding integer columns with decimal values. 在将整数列与十进制值相乘并添加整数列时,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();
Surely this isn't the expected/correct behaviour? 当然这不是预期/正确的行为? I would expect the WithDecimals value to be 50.5 (not 51). 我希望WithDecimals值为50.5(而不是51)。 Am I overlooking something simple? 我忽略了简单的事情吗? How can I ensure that WithoutDecimals doesn't get rounded without changing the type of the other constants? 如何在不更改其他常量类型的情况下确保WithoutDecimals不会被舍入?
The generated SQL for WithFloats and WithDecimals (respectively): 为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
Explicitly define the column type, as well as the precision and scale of the decimal field by using a data-annotation 通过使用数据注释显式定义列类型以及十进制字段的精度和小数位数
[Column(TypeName = "decimal(5,2)")]
public decimal MyDecimal { get; set; }
You can find the default LINQ-to-SQL CLR type mappings, which applies when using EF, here . 您可以在此处找到默认的LINQ-to-SQL CLR类型映射,适用于使用EF时。
Read up on T-SQL numeric and decimal datatypes here . 在这里阅读T-SQL数字和十进制数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.