PagedList error: The method 'OrderBy' must be called before the method 'Skip'

Theo picture Theo · Aug 12, 2014 · Viewed 25.2k times · Source

Here's the full error message: The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'

In the "PurchaseOrderController" I have added this code to the index method:

// GET: PurchaseOrder
    public ActionResult Index(int? page)
    {
        return View(db.PurchaseOrders.ToPagedList(page ?? 1, 3));
    }

Also in the Index View for "PurchaseOrders" I have added this code:

    @using PagedList;
@using PagedList.Mvc;
@model IPagedList<PurchaseOrders.Models.PurchaseOrder>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.First().PurchaseRequest_)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.First().Date)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.First().Requestor)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.First().Vendor)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.First().DateOrdered)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.First().ConfirmedWith)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.First().WorkOrder_)
        </th>
        <th></th>
    </tr>

Answer

user3559349 picture user3559349 · Aug 12, 2014

You need to add an .OrderBy() in the expression:

return View(db.PurchaseOrders.OrderBy(i => i.SomeProperty).ToPagedList(page ?? 1, 3));

The .ToPageList() method uses .Skip() and .Take() so it must be passed an ordered collection first.