c# - linq to entities 与 linq to objects 中的 Math.Round

标签 c# entity-framework entity-framework-6

以下行为是不同的并且很难管理,这取决于查询是否被执行:

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/

相关文章:

c# - AJAX由下拉列表触发的ModalPopup

c# - DotNet 核心 Web API 依赖注入(inject)范围和处置

c# - 我如何检查并终止我的应用程序的另一个实例?

c# - Entity Framework 核心 : How to dynamically get the DbSet from a derived Type?

.net - 如何在 Entity Framework (EF6) Code-First 中映射冗余关系

c# - 如何添加没有相关实体但保存关系的实体?

java - hibernate 多对多: A collection with cascade all-delete-orphan

c# - 处理谷歌地图的纬度/经度坐标

c# - 带有 Identity 2 和 EntityFramework 6 的 ASP.NET Core MVC(甲骨文)

c# - 两个实体之间的可选关系