Home > Net >  IQueryable.OrderBy is not working with IComparer in EF Core
IQueryable.OrderBy is not working with IComparer in EF Core

Time:03-19

We have a signature of a method in a IQueryable interface:

public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer);

I am trying to implement this call like

var result = await DbSet.OrderBy(e => e.Type, new EntityTypeComparer()).ToListAsync();

But it throws the exception "The LINQ expression could not be translated".

Can you share any working examples of IComparer with EF Core? Or how I can implement custom sorting logic for int property in EF Core?

P.S. Microsoft docs says that IComparer is not supported. But what do we need IQueryable.OrderBy with IComparer parameter for?

CodePudding user response:

That is already explained to this case here Is it possible to use IComparable to compare entities in Entity Framework?

The short Answer is No, you cant do that.

EF requires all operations to be able to execute 100% server-side. Supporting IComparable or IEquatable would require EF to be able to translate arbitrary IL into SQL, which it can't yet do.

  • Related