2

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

        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();
        }

我的问题是,当我进行 raven 查询时,我的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
        };
    }
4

1 回答 1

4

我自己想通了。事实证明,RavenQueryStatistics通过引用设置TotalResults,并且只有在解决结果后才能使用总数。(我原本以为它是单独前往数据库的。)

    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)
        };
    }
于 2012-05-20T17:28:45.063 回答