3

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
WhiskerBiscuit
  • 4,795
  • 8
  • 62
  • 100

2 Answers2

5

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).

ken2k
  • 48,145
  • 10
  • 116
  • 176
3

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();
Marco
  • 22,856
  • 9
  • 75
  • 124