Reputation: 396
I want to create pagination my LINQ query gives error:
var query = from c in db.Projects.Take(2).Skip(2) orderby c.ProjectId descending select c;
gives the following error:
$exception {"The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'."} System.Exception {System.NotSupportedException}
Upvotes: 0
Views: 372
Reputation: 6341
Try:
var query = (from c in db.Projects orderby c.ProjectId descending select c).AsEnumerable().Skip(2).Take(2)
Or More efficient (Credit to Jon Skeet)
var query = (from c in db.Projects orderby c.ProjectId descending select c).Skip(2).Take(2)
Upvotes: 4
Reputation: 1501163
The error describes exactly what is required - your sequence needs to be ordered before skip/take many any sense. You already know what ordering you want - you've just got to make it happen earlier in the logical pipeline than the paging. Additionally, there's really no benefit in using a query expression here. I suggest you use:
var query = db.Projects
.OrderByDescending(c => c.ProjectId)
.Skip(2)
.Take(2);
(That can all be in one line if you really want it to be, but I find it simpler to understand the pipeline if it's laid out vertically.)
Note that I've also inverted the order of Skip
and Take
- you almost never want Take
before Skip
... in your sample code, you've shown Take(2).Skip(2)
which could never return any results... the result of the Take(2)
part is a sequence with at most two results, and then the Skip(2)
is skipping the first two of those results... leaving nothing. Typically you have something like:
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
Upvotes: 4