2012-05-20 100 views
2

我在創建尋呼包裝的擴展方法這樣的邏輯: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 
     }; 
    } 

回答

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