2

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?

misha130
  • 5,457
  • 2
  • 29
  • 51
  • 4
    Arbitrary comparers obviously cannot be supported since you can't run C# code on the database end. The replacement depends on exactly what you're doing in your comparer. As to why it's there, some standard comparers like `StringComparer.OrdinalIgnoreCase` may well be supported by LINQ providers (which encompass more than just databases, in any case). – Jeroen Mostert Mar 18 '22 at 12:42
  • https://stackoverflow.com/a/57971185/3844386 .. – saravanan049 Mar 18 '22 at 12:45

1 Answers1

1

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.

Darkk L
  • 889
  • 1
  • 4
  • 14
  • 1
    I like the hopeful addition of "yet" -- technically it's absolutely feasible to implement an IL interpreter in T-SQL. Performance would be horrific, but let's ignore that bit. :) – Jeroen Mostert Mar 18 '22 at 13:12
  • That's true man , I will allow myself to say "maybe they will" just for you :) – Darkk L Mar 18 '22 at 14:11