0

I have some code

foreach (var prop in typeof(Container).GetProperties())
{
  if (sortField.IndexOf(prop.Name, StringComparison.OrdinalIgnoreCase) >= 0)
  {
    containers = sortDir == "desc"
                 ? containers.OrderByDescending(x => prop.GetValue(x, null))
                 : containers.OrderBy(x => prop.GetValue(x, null));
  }
}
var total = containers.Count();
//Take and Skip operations

containers = containers.Include(x => x.MasterType);
...

Properties for sorting can be int, DateTime, string. If I do simple containers = containers.OrderBy(x => x.Id) then everything is fine.

but in my case above on row var total = ... I got the exception LINQ expression could not be translated ...

The main thing is that after sorting/taking/skipping, I do some .Include operations to reduce the time of executing a query.

What's the reason? Why does simple sorting works but dynamic not?

How can I resolve this issue? What's the best way to do such things?

Muzammil Ismail
  • 257
  • 3
  • 7
A. Gladkiy
  • 2,926
  • 4
  • 30
  • 70
  • 1
    You can't use any custom calls (including reflection) inside `IQueryable` expression tree. You have to build expressions similar to compiler. For instance, something like here https://stackoverflow.com/questions/39908403/how-to-use-a-string-to-create-a-ef-order-by-expression/39916384#39916384. Also make sure to use `OrderBy{Descending}` for the first and `ThenBy{Descending}` for the next(s), otherwise you'll end up sorting just by the last property. – Ivan Stoev Oct 11 '21 at 10:07

0 Answers0