Paging a changable collection
Paging using LINQ can be easily done using the Skip() and Take() extensions.
I have been scratching my head for quite some time now, trying to find a
good way to perform paging of a dynamic collection of entities - i.e. a
collection that can change between two sequential queries.
Assume a query that without paging will return 20 objects of type MyEntity.
The following two lines will trigger two DB hits that will populate
results1 and results2 with all of the objects in the dataset.
List<MyEntity> results1 = query.Take(10).ToList();
List<MyEntity> results2 = query.Skip(10).Take(10).ToList();
Now let's assume the data is dynamic, and that a new MyEntity is inserted
into the DB between the two queries, in such a way that the original query
will place the new entity in the first page.
In that case, results2 list will contain an entity that also exists in
results1,
causing duplication of results being sent to the consumer of the query.
Assuming a record from the first page was deleted, it will result missing
a record that should have originally appear on results2.
I thought about adding a Where() clause to the query that verify that the
records where not retrieved on a previous page, but it seems like the
wrong way to go, and it won't help with the second scenario.
I thought about keeping a record of query executions' timestamps,
attaching a LastUpdatedTimestamp to each entity and filtering entities
that were changed after the previous page request. That direction will
fail on the third page afterwards...
How is this normally done?
Is there a way to run a query against an old snapshot of the DB?
No comments:
Post a Comment