JamesZeinzu
JamesZeinzu

Reputation: 245

'Linq to Entities does not recognize the method' when ordering by Object

I have seen many SO questions surrounding this topic but I cant find the solution to my particular situation, I have the following statement:

return (from Animals in ctx.Animals
                orderby sortStrategy.Sort(Animals)
               descending
                select Animals).AsQueryable();

sortStrategy.Sort just returns the Object that I want to sort Animals by. However this throws the following error:

'LINQ to Entities does not recognize the method 'System.Object Sort(AnimalLibrary.Animal)' method, and this method cannot be translated into a store expression.'

I believe this is because Linq doesn't understand how to execute sortStrategy.Sort, but im not sure how to actually fix this problem. Any help would be appreciated.

Cheers, James.

Upvotes: 0

Views: 125

Answers (3)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 62012

(This answer was promoted from a comment.)

If you want to fetch the data to memory and do the sorting there, probably

(from Animals in ctx.Animals.AsEnumerable() /* NB! */
orderby sortStrategy.Sort(Animals) descending
select Animals)

will work.

Upvotes: 1

Rawling
Rawling

Reputation: 50204

You say sortStrategy.Sort returns some property of the Animal, so you may be able to redefine your strategy class as something like

class SortStrategy<T>
{
    public Expression<Func<Animal, T>> Sort { get; set; }
}

then build up your strategies like

var sortByAgeStrategy = new SortStrategy<int> { Sort = a => a.Age };
var sortByNameStrategy = new SortStrategy<string> { Sort = a => a.Name };

at which point you can pick one of these strategies and call LINQ like

IQueryable<Animal> sorted =
    from a in animals
    orderby someSortStrategy.Sort descending
    select a;

Upvotes: 0

Steve Wilkes
Steve Wilkes

Reputation: 7135

As indicated in the comments, this will not work. When you pass a query to Linq-To-Entities, it translates that query into SQL - it requires that everything you pass it in the query can be translated to SQL as-is - it will not execute arbitrary C# methods in order to obtain a value which it can then embed in the SQL it produces.

If you want to order by Animal name, your query will have to include order by Animals.Name. If you want to order by the result of sortStrategy.Sort you'll either have to execute the query without sorting then perform the sorting on the results in memory using Linq-To-Objects, or use Dynamic Linq to embed the result of sortStrategy.Sort() in a string query which can then be translated into an expression.

Upvotes: 0

Related Questions