2

How can I make this orderby code work thisEntity Framework query

This is the orderby part of the query

orderby (double)b.score * Math.Pow( (1 + Math.Log(b.total_votes)), 0.2) 

I get this exception:

LINQ to Entities does not recognize the method 'Double Log(Double)' method, and this method cannot be translated into a store expression.

How can I make it work?

Liron Harel
  • 10,819
  • 26
  • 118
  • 217

2 Answers2

2

Entity Framework tries to translate Math.Log function into SQL so that it could be executed against the DB but it doesn't know how to do that for Math.Log.

  • One solution is to retrieve all your items into memory using .ToList(), and execute Math.Log in memory using LINQ to Objects.
  • Another solution is to use the existing SqlFunctions.Log.

This is how you could write your orderby:

orderby (double)b.score * Math.Pow((1 + SqlFunctions.Log(b.total_votes) ?? default(double)), 0.2) 

And if there are just 10 records, this is how you can sort in memory:

from b in _dataContext.MyTypes.ToList() orderby (double)b.score * Math.Pow((1 + Math.Log(b.total_votes)), 0.2) select b;
sachin
  • 2,341
  • 12
  • 24
  • what is the type of total_votes? Try casting b.total_votes to double. – sachin Sep 16 '16 at 08:20
  • I cast to double and after I run the code, I get this exception: The specified method 'System.Nullable`1[System.Double] Log(System.Nullable`1[System.Double])' on the type 'System.Data.Entity.SqlServer.SqlFunctions' cannot be translated into a LINQ to Entities store expression. My code: orderby (double)b.score * Math.Pow((1 + System.Data.Entity.SqlServer.SqlFunctions.Log((double)b.total_votes) ?? default(double)), 0.2). Total Votes is of type long. – Liron Harel Sep 16 '16 at 08:21
  • 1
    I think you can go with 2nd approach as you're saying that there are only 10 records. – sachin Sep 16 '16 at 08:24
  • what .MyTypes.ToList() means? – Liron Harel Sep 16 '16 at 08:40
  • The returned results is a new type (I made a class for it called sortedResults) – Liron Harel Sep 16 '16 at 08:42
  • I was using MyTypes for a placeholder as I didn't know your type :) – sachin Sep 16 '16 at 09:13
0

There are a lot of same questions: this, that, etc. Try to use SqlFunctions.Log

Community
  • 1
  • 1
Alexander
  • 560
  • 3
  • 14