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?