Ajendra Prasad
Ajendra Prasad

Reputation: 327

Adding 'Skip' throws exception: The method 'Skip' is only supported for sorted input in LINQ to Entities

I am trying to fetch all rows for n groups while skipping x no of groups so I don't have to execute all records at once. In this way I can implement pagination to load data faster.

The following code is working fine (without skipping) where I am fetching all records from the first 2 groups (grouped by same Id).

IOrderedQueryable<Patient> query = query.OrderBy(r => r.Id);

IQueryable<Patient> groupedQuery = query.GroupBy(x => x.Id).Take(2).SelectMany(g => g);

But to implement pagination, when I am trying to add 'Skip' in the following way and calling groupedQuery.ToList();.

IQueryable<Patient> groupedQuery = query.GroupBy(x => x.Id).Skip(2).Take(4).SelectMany(g => g);

It throws the exception:

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

Can someone please suggest the right way of doing it.

Upvotes: 1

Views: 1042

Answers (1)

Jason Tang
Jason Tang

Reputation: 111

If order of groups doesn't matter to you, try adding an OrderBy() method before the Skip as below:

query.GroupBy(x => x.Id).OrderBy(YourOrderCriterion).Skip(2).Take(4).SelectMany(g => g);

The reason for the error is that as Skip is commonly used for paging, if you don't guarantee that your data is ordered a certain way, then the order used for retrieving the first page may differ from the order used for subsequent pages.

Upvotes: 6

Related Questions