Math.Round in linq to entities vs linq to objects

c# entity-framework entity-framework-6

Question

The behavior of the following are different and it's hard to manage, depending on if the query was executed or not:

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
} 

Of course my actual code perform an operation on x. this is for simplicity.

I know there is Math.Round with MidpointRounding but it's not supported by 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.

My question is, other than executing the query and rounding in memory, is there a way to have the same behavior in c# and Linq to Entities?

Is there a way to set the default behavior of Math.Round to always use MidpointRounding.AwayFromZero?

1
3
10/31/2018 7:42:52 PM

Accepted Answer

Based on the answer to this question it doesn't look like what you're asking is possible. The answer to that question also recommends fetching the data using AsEnumerable, as other comments on this question have, and doing your rounding on the in-memory data using a local query.

var rawData = db.Entities.Select(x => 0.5); 
var rounded =  rawData.AsEnumerable().Select(x => Math.Round(x, MidpointRounding.AwayFromZero));
0
10/31/2018 1:13:36 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow