以下行为是不同的并且很难管理,这取决于查询是否被执行:
using (var db = new DbContext())
{
db.Entities.Select(x => Math.Round(0.5)).First(); // return 1
db.Entities.ToList().Select(x => Math.Round(0.5)).First(); // returns 0
db.Entities.AsEnumerable().Select(x => Math.Round(0.5)).First(); // returns 0
}
当然,我的实际代码对x
执行操作。这是为了简单起见。
我知道有 Math.Round with MidpointRounding但 Linq to Entities 不支持它:
LINQ to Entities does not recognize the method 'Double Round(Double, System.MidpointRounding)' method, and this method cannot be translated into a store expression.
我的问题是,除了在内存中执行查询和舍入之外,有没有办法在 C# 和 Linq to Entities 中具有相同的行为?
有没有办法将 Math.Round 的默认行为设置为始终使用 MidpointRounding.AwayFromZero
?
最佳答案
基于对 this question 的回答它看起来不像你问的是可能的。该问题的答案还建议使用 AsEnumerable 获取数据,正如对这个问题的其他评论一样,并使用本地查询对内存中的数据进行舍入。
var rawData = db.Entities.Select(x => 0.5);
var rounded = rawData.AsEnumerable().Select(x => Math.Round(x, MidpointRounding.AwayFromZero));
关于c# - linq to entities 与 linq to objects 中的 Math.Round,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53069706/