Search code examples
c#entity-frameworklinqiqueryable

Sorting IQueryable by other List of IDs causes SystemInvalidOperationException


I have a IQueryable of a custom object that contains multiple properties, however, only the ID should be relevant for this. I made a method that provides me with a List of IDs based on some other properties that tells me how to sort the IQueryable object.

I then try to order it like this: query = query.OrderBy(q => sortedList.IndexOf(q.ID));

No problem occurs yet, however, if I try to perform other actions on the IQueryable such as performing a .ToList() or getting a page of data I am met by a InvalidOperationException saying that the LINQ query could not be translated.

I expected the IQueryable object to be correctly sorted/ordered.


Solution

  • When using Entity Framework, the OrderBy expression is translated into a SQL query (or equivalent, depending on your database provider) so that it can be executed at the database server. This happens at the point the query is enumerated, in your case when you call ToList.

    Entity Framework is not able to translate the function sortListed.IndexOf to a SQL statement because the database doesn't have a copy of the sorted list (which existed in memory) and this is why you see the error. EF can only translate relatively simple expressions.

    You will need to try to find another way to order your query, but to get exactly what you want will depend on how sortedList has been ordered.

    Hopefully this will point you in the right direction.

    UPDATE...

    To alphabetically order the IQueryable based on different properties depending on a property on each item called Flag, you can do this:

    query = query.OrderBy(q => q.Flag ? q.PropertyA : q.PropertyB)