views:

44

answers:

2

What could be causing this problem?

public ActionResult Index(int page = 0)
{
    const int pageSize = 3;
    var areas = repo.FindAllAreas();
    var paginatedArea = new PaginatedList<Area>(areas, page, pageSize);

    return View(paginatedArea);
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UTEPSA.Controllers
{
    class PaginatedList<T> : List<T>
    {
        public int PageIndex { get; private set; }
        public int PageSize { get; private set; }
        public int TotalCount { get; private set; }
        public int TotalPages { get; private set; }
        public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize)
        {
            PageIndex = pageIndex;
            PageSize = pageSize;
            TotalCount = source.Count();
            TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize);
//ERROR HERE->>this.AddRange(source.Skip(PageIndex * PageSize).Take(PageSize));
        }
        public bool HasPreviousPage
        {
            get
            {
                return (PageIndex > 0);
            }
        }
        public bool HasNextPage
        {
            get
            {
                return (PageIndex + 1 < TotalPages);
            }
        }
    }
}

Any suggestions?

+1  A: 

Seems like the error is exactly what it is says. "Skip is only allowed on Sorted inputs". Searching for this error, I've found this:

http://weblogs.asp.net/rajbk/archive/2009/09.aspx

It should be fixed if you include an OrderBy before Skip:

source.orderBy(???).Skip(PageIndex * PageSize).Take(PageSize));

which might be a problem since you are passing a generic object T. You might need to expand your class to receive another parameter to indicate the order by element.

I hope this helps.

cheers, Wagner.

Wagner Silveira
From the article: This issue seems to have been fixed in the .NET 4.0 framework [for linq-to-sql, not linq-to-entities]...
jeroenh
A: 

An IQueryable does not have an order, so saying "ignore the next x elements" doesn't make any sense.

If you include an order by clause (or possibly an AsEnumerable() call - untested) then your data takes an order and Skip and Take are now sensible.

Zooba
You don't want to add AsEnumerable. This would defeat the main reason of paging which is to only fetch a limited amount of data from the database... Adding AsEnumerable() will pull in EVERYTHING, and apply the paging in-memory.
jeroenh
Have you tested this (or have a source), or are you assuming it? Calling ToList or ToArray will certainly pull in everything, but there is nothing in the contract of AsEnumerable that forces it to retrieve all data before returning the first (and subsequent) elements.
Zooba