RavenDB获取查询无效的总计数

时间:2012-05-20 17:22:28

标签: c# ravendb

我在一个创建分页包装器的扩展方法中有这个逻辑:

        int total = 0;
        if (query is IRavenQueryable<T>)
        {
            RavenQueryStatistics stats;
            var rQuery = (IRavenQueryable<T>)query;
            rQuery.Statistics(out stats);
            total = stats.TotalResults;
        }
        else
        {
            total = query.Count();
        }

我的问题是,当我执行乌鸦查询时,我的 stats.TotalResults 为零,除非我在调试期间将鼠标悬停在 rQuery 上尝试扩大结果。

我在这里做错了什么?如何让乌鸦始终如一地向我提供我需要的结果?

以下是整个方法:

    public static PagingModel<T> Page<T>(this IEnumerable<T> query, int page, int count)
    {
        if (page < 1)
            throw new ArgumentOutOfRangeException("Page is one-based and must be greater than zero");

        int total = 0;
        if (query is IRavenQueryable<T>)
        {
            RavenQueryStatistics stats;
            var rQuery = (IRavenQueryable<T>)query;
            rQuery.Statistics(out stats);
            total = stats.TotalResults;
        }
        else
        {
            total = query.Count();
        }

        var results = query
            .Skip((page - 1) * count)
            .Take(count)
            .ToArray();

        return new PagingModel<T>()
        {
            Page = page,
            Rows = results,
            Total = total /count
        };
    }

1 个答案:

答案 0 :(得分:4)

我自己想通了。事实证明, RavenQueryStatistics 通过引用设置了 TotalResults ,并且总数仅在结果解析后才可用。 (我原本以为它单独去了DB。)

    public static PagingModel<T> Page<T>(this IEnumerable<T> query, int page, int count)
    {
        RavenQueryStatistics stats = null;
        if (page < 1)
            throw new ArgumentOutOfRangeException("Page is one-based and must be greater than zero");

        if (query is IRavenQueryable<T>)
        {
            var rQuery = (IRavenQueryable<T>)query;
            rQuery.Statistics(out stats);
        }

        var results = query
            .Skip((page - 1) * count)
            .Take(count)
            .ToArray();
        var total = stats == null ? query.Count() : stats.TotalResults;
        return new PagingModel<T>()
        {
            Page = page,
            Rows = results,
            TotalPages = (int)Math.Ceiling((double)total / (double)count)
        };
    }