I am trying to take the absolute value in a linq to entities query and getting an exception

I am making a call to Math.Abs() inside of my linq to entities query, e.g.
var query = from mySource
select new {absv = Math.Abs((double) mySource.myValue)}
//the query above is not necessarily compiling, I just paraphrased it, in my application I have the syntax right // but the following exception happens:
"LINQ to Entities does not recognize the method 'Double Abs(Double)' method, and this method cannot be translated into a store expression."

mySource is coming from a sql table and myValue represents a nullable column of type FLOAT

All I am trying to do is to take the absolute value of the myValue column inside of my projection, but I am getting this exception.  

Any ideas?
Who is Participating?
Refael AckermannConnect With a Mentor Commented:
L2E is trying to translate the call the Math.Abs to something is can run in the DB. Unfortunatly it doesn't have a mapping so it fails.
You should be able to do a "lifted" projection after the first projection.

var q = from mySource
        select new {v = (double)mySource.myValue};
var q2 = from x in q.ToList() // ToList causes "lifting"
         select new {absv = Math.Abs(x.v)};

Open in new window

izmikeAuthor Commented:
Thanks for the comment, that does shed light on things, however this absolute value column is one of many columns that are being used to produce a report, using the "lifting" technique here seems like it will bloat the code and cause a lot of repetition.

I have opted to use a conditional here instead, I knew I could do this but preferred to actually use the ABS function if L2E supported it.  

var q = from mySource
        select new {absv = mySource.myValue <0 ? -1*mySource.myValue : mySource.myValue};

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.