I am retriveing some data using Entity Framework like so:
var items = GetItems(storeNumber); Sort(items); Page(items); return await items.ToListAsync(); I have these private helper methods:
private IQueryable<Item> GetItems(string storeNumber) { return _dbContext.Items.Where(x => x.StoreNumber == storeNumber); } I sort the results using Dynamic LINQ.
private void Sort(IQueryable<Item> items, string fieldToSort, string sortDirection) { items = items.OrderBy($"{fieldToSort} {sortDirection}"); } In my Page method I get the exception
The method 'OrderBy' must be called before the method 'Skip'
private void Page(IQueryable<Item> items, int skip, int take) { items = items.Skip(skip).Take(take); } I had suspected that the reason for the error was because items needs to be IOrderedQueryable<Item> but there is no overload for the Dynamic LINQ OrderBy which returns IOrderedQueryable<T>. If I extract the Sort and Page code into the same method, using var it's no longer an issue, it infers the type. The problem seems to be using the IQueryable interface when sorting and paging. Is there a way I can break up this logic into separate methods but still use Dynamic LINQ for sorting?
Any help is much appreciated.
Sortmethod has no effect (as wellPageand any LINQ method) because you are not returning the result with applied queryable operator. Consider changing them to a methods returningIQueryable<Item>, e.g.private IQueryable<Item> Sort(...) { return items.OrderBy(...); }. I don't forget to use the returned result as well.ref IQueryable<Item> items, or you need return the local variableitems. Usingreturn ...is by far the most common approach.IQueryablereference. Instead, they return a new reference which needs to be used. If you mean that you assignitemsvariable inside thevoidmethod, you might consider reading aboutrefarguments in C#.