Fork me on GitHub

Paging Edit on GitHub


For paged access to data in Marten, just use the Take() and Skip() Linq operators. To get the total number of documents matching a query without having to execute the query twice, use the new Stats() Linq operator to also capture the total as shown in this sample:


[Fact]
public void can_get_the_total_in_results()
{
    var count = theSession.Query<Target>().Count(x => x.Number > 10);
    count.ShouldBeGreaterThan(0);

    // We're going to use stats as an output
    // parameter to the call below, so we
    // have to declare the "stats" object
    // first
    QueryStatistics stats = null;

    var list = theSession
        .Query<Target>()
        .Stats(out stats)
        .Where(x => x.Number > 10).Take(5)
        .ToList();

    list.Any().ShouldBeTrue();

    // Now, the total results data should
    // be available
    stats.TotalResults.ShouldBe(count);
}

For the sake of completeness, the SQL generated in the operation above by Marten would be:

select d.data, d.id, count(1) OVER() as total_rows from public.mt_doc_target as d where CAST(d.data ->> 'Number' as integer) > :arg0 LIMIT 5

The Stats() Linq operator can be used in conjunction with Include() and within batch queries. Marten does not yet support using Stats() within the compiled query.