简体   繁体   中英

Linq to entities, Paging in EF6: alternative for SkipWhile?

I want to use linq to show a sequence in pages, where operators can request to show the previous page or the next page. Each page has a constant page size.

Several questions on stackoverflow handle how to do this, ao Paging with LINQ for objects

The solutions suggest using Skip and Take. This works fine as long as the sequence does not change while viewing it. But if items are inserted or removed while viewing a page, you'll miss items.

Example: page size = 10 items. I am viewing page 8 (zero based) containing items 80 to 89. Obviously if I press pageup I want to see items 70 to 79. However, if someone inserted 5 items somewhere near item 25 (so way out of the page I am viewing), I will miss some items.

The cause of this is because the software thinks that page 8 is being viewed, while because of the insertions I am in fact viewing page 8.5.

So instead of using Skip(pagenumber * pagesize) I should use a function that returns the elements after a given element, or before a given item in the sequence. Normally SkipWhile(...) would be enough:

private static IEnumerable<T> ItemsAfter(this IEnumerable<T> source,
    Func<TSource, bool> predicate, int pageSize)
{
   return source.Orderby(...)
                .SkipWhile(predicate)
                .Take(pageSize)
}

However SkipWhile is not recognized by LINQ to entities. So is there an alternative?

Addition: What I want is: given an element from a sorted sequence, give me the next 10 elements (or the previous 10) I think the solution is somewhere near SQL Fetch Next and Fetch Prior, but haven't found a good explanation for it yet.

It is very hard to come up with a replacement for SkipWhile because EF does not support any of the numbering functions either. Therefore everything based on relative order is hard.

Here, you probably can make use of the following query form:

   return source
            .Where(x => x.PositioningKey > lastSeenValue)
            .Orderby(x => x.PositioningKey)
            .Take(pageSize)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM