Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OrderByDescending with Skip and Take in LINQ shows error

My linq is something

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

I am getting following exception when the above code is run

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

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

Can someone suggest me alternative ?

like image 548
Isaiyavan Babu Karan Avatar asked Aug 02 '13 05:08

Isaiyavan Babu Karan


1 Answers

This works with EF5. (.net 4.5) I cant see anything wrong with your code. Are you sure you had the method sequence right when 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);
    }
like image 195
phil soady Avatar answered Oct 11 '22 13:10

phil soady