How to implement the equivalent functionality to a custom IComparer for Linq to Entities OrderBy()?

StackOverflow https://stackoverflow.com/questions/10643712

Domanda

How can I implement the equivalent to a custom IComparer for Linq to Entities OrderBy()?

A custom comparer is not supported in Linq to Entities as MSDN documentation states:

Most of the LINQ ordering methods are supported in LINQ to Entities, with the exception of those that accept an IComparer, because the comparer cannot be translated to the data source. For more information, see Standard Query Operators in LINQ to Entities Queries.

È stato utile?

Soluzione

If you want to use a custom IComparer, you need to first ask yourself whether it's possible to do the sorting in the database. If it's not, just call AsEnumerable on the sequence, and then sort it on the server.

If you can (and want to) sort it in the database, then you'll need to think through what conversions need to be made so that the sorting can happen. If you have a complex conversion, you could write it as a SQL function, and add it to your data context:

from e in context.Entities
let hours = context.Get32HourValue(e.Time)
orderby hours
select e
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top