Linq & Paging - Unable to return paged data with an OrderBy
Asked Answered
I

1

10

I've been trying to implement a simple paging system on a WCF service I've written that uses Linq To SQL To query a database but seem to be going from one problem to another.

I want the WCF Service to return a list of this type:

[DataContract]
public class TestType
{
    [DataMember]
    public int ID { get; set; }
    [DataMember]
    public string Name { get; set; }
}

and I'm using the following code:

int pageNumber = 0;
int pageSize = 25;

List<TestType> results = (from caseTypes in context.cch
                          select new TestType()
                          {
                              ID = caseTypes.cch_id,
                              Name = caseTypes.cch_case_ref
                          }                               
                          ).Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList<TestType>(); 

However, when i run the code I get the error:

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

So, if I change the code to add an orderby:

List<TestType> results = (from caseTypes in context.cch
                          orderby caseTypes.cch_id
                          select new TestType()
                          {
                               ID = caseTypes.cch_id,
                               Name = caseTypes.cch_case_ref
                          }                               
                          ).Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList<TestType>(); 

I then get greeted by the error message:

Count must have a non-negative value.
Parameter name: count

Am I even approaching this paging the correct way?

Isabelisabelita answered 19/10, 2011 at 14:9 Comment(1)
.Skip((0 - 1) * 25) == -25. How do you skip -25?Vulpine
S
33

You initialized the page number as 0 so -1 is the skip parameter it's complaining about. Initialize the page as 1.

Soupandfish answered 19/10, 2011 at 14:15 Comment(2)
I can't believe I've been that stupid. In my defence, I've had nothing but problems with this since I started and this will be the end of a very frustrating day. Thanks Justin!Isabelisabelita
@Isabelisabelita lol all programmers have those days, sometimes we just need a fresh set of eyes to spot the obvious.Soupandfish

© 2022 - 2024 — McMap. All rights reserved.