.netwcfpaginationlinq-to-sql

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


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?


Solution

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