OrderByDescending with Skip and Take in LINQ shows an error

My linq is something

GetPublishedArticleList().Where(x => x.Category.CatName == catName).OrderByDescending(x=>x.PublishedDate).Skip(skip).Take(last); 

I get the following exception when the above code is executed

The Skip method is only supported for sorted input in LINQ to Entities. The OrderBy method must be called before the Skip method.

Well, I want LINQ to understand that I need to order the data first in descending order, and then apply Skip and Take. (well, this code works when OrderByDescending is replaced by OrderBy)

Can someone suggest me an alternative?

+6
source share
1 answer

This works with EF5. (.net 4.5) I do not see anything wrong with your code. Are you sure that you had a sequence of methods immediately during testing? Was the source type Iqueryable or Iqueryable?

 public virtual IQueryable<TPoco> GetSortedPageList<TSortKey>(Expression<Func<TPoco, bool>> predicate, Expression<Func<TPoco, TSortKey>> sortBy, bool descending, int skipRecords, int takeRecords) { if (!descending) { return Context.Set<TPoco>() .Where<TPoco> predicate) .OrderBy(sortBy) .Skip(skipRecords) .Take(takeRecords); } return Context.Set<TPoco>() .Where<TPoco>(predicate) .OrderByDescending(sortBy) .Skip(skipRecords) .Take(takeRecords); } 
+1
source

Source: https://habr.com/ru/post/950872/


All Articles