Почему получаю исключение The LINQ expression 'DbSet .OrderBy(a => a.GetType().GetProperty(__sortBy_0)
Делаю сортировку таким способом
private IQueryable<Author> SortAuthor(string sortBy, string typeSort, IQueryable<Author> authors)
{
if (typeSort is "Desc")
{
authors = authors.OrderByDescending(a => a.GetType().GetProperty(sortBy).GetValue(a, null));
}
if (typeSort is "Asc")
{
authors = authors.OrderBy(a => a.GetType().GetProperty(sortBy).GetValue(a, null));
}
return authors;
}
В итоге получаю исключение
The LINQ expression 'DbSet<Author>
.OrderBy(a => a.GetType().GetProperty(__sortBy_0).GetValue(
obj: a,
index: null))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync()
Подскажите пожалуйста как исправить)
Ответы (1 шт):
Автор решения: aepot
→ Ссылка
А если так попробовать?
enum SortOrder
{
Asc,
Desc
}
private IQueryable<Author> SortAuthor<TKey>(Expression<Func<Author, TKey>> sortBy, SortOrder typeSort, IQueryable<Author> authors)
{
return typeSort switch
{
SortOrder.Desc => authors.OrderByDescending(sortBy),
_ => authors.OrderBy(sortBy),
};
}
authors = SortAuthor(a => a.Name, SortOrder.Asc, authors);