Reputation: 5157
I have a simple table (SQL server and EF6) Myvalues, with columns Id & Value (double)
I'm trying to get the sum of the natural log of all values in this table. My LINQ statement is:
var sum = db.Myvalues.Select(x => Math.Log(x.Value)).Sum();
It compiles fine, but I'm getting a RTE:
LINQ to Entities does not recognize the method 'Double Log(Double)' method, and this method cannot be translated into a store expression.
What am I doing wrong/how can I fix this?
FWIW, I can execute the following SQL query directly against the database which gives me the correct answer:
select exp(sum(LogCol)) from
(select log(Myvalues.Value) as LogCol From Myvalues
) results
Upvotes: 3
Views: 2429
Reputation: 23945
As EF cannot translate Math.Log()
you could get your data in memory and execute the function form your client:
var sum = db.Myvalues.ToList().Select(x => Math.Log(x.Value)).Sum();
Upvotes: 3
Reputation: 49013
LINQ tries to translate Math.Log
into a SQL command so it is executed against the DB.
This is not supported.
The first solution (for SQL Server) is to use one of the existing SqlFunctions
. More specifically, SqlFunctions.Log
.
The other solution is to retrieve all your items from your DB using .ToList()
, and execute Math.Log
with LINQ to Objects (not LINQ to Entities).
Upvotes: 5