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

1

16

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>
Espalier answered 12/8, 2014 at 12:28 Comment(0)
L
34

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.

Libbi answered 12/8, 2014 at 12:38 Comment(2)
Thank you. How did you know that I needed an .OrderBy()?Espalier
Presumably because the error message specifically told you so? :D I personally stopped using PagedList and just made my own viewmodel that I can pass the Skip and Take values to and keep track of what page I am on, how many results I have, etc. Makes it more transparent and I can use the viewmodel for other things too.Shuffleboard

© 2022 - 2024 — McMap. All rights reserved.