2011-10-20 96 views
2

我正在動態構建一個需要實現分頁的nhibernate投影查詢。喜歡的東西...集合分頁投影nhibernate查詢的總計結果

var projections = Projections.ProjectionList(); 
foreach (var p in projection.Projections) 
{ 
    IProjection newProjection = null; 
    switch (p.AggregateFunc) 
    { 
     case AggregateFuncTypeEnum.GroupProperty: 
      newProjection = Projections.GroupProperty(p.Path); 
      break; 
     case AggregateFuncTypeEnum.Sum: 
      newProjection = Projections.Sum(p.Path); 
      break; 
     default: 
      newProjection = Projections.Property(p.Path); 
      break; 
    } 
    projections.Add(newProjection, p.Name); 
} 
criteria.SetProjection(projections).SetResultTransformer(new AliasToBeanResultTransformer(projectionType)); 

我能得到前15分的結果,像這樣

criteria.SetFirstResult(0); 
criteria.SetMaxResults(15); 
var results = criteria.List(); 

但我也需要發送另一個查詢來獲取的記錄總數,但到目前爲止,我已經失敗弄清楚這一點。該投影仍然需要應用,即如果結果按'代碼'分組並且'成本'之和那麼100條記錄可能返回20行,並且這是我感興趣的20條。

我該如何獲得將返回的記錄總數?由於

回答

0

也許這:

var rowcount = CriteriaTransformer.Clone(criteria); 

var goupprojections = Projections.ProjectionList(); 
var projections = Projections.ProjectionList(); 
foreach (var p in projection.Projections) 
{ 
    IProjection newProjection = null; 
    switch (p.AggregateFunc) 
    { 
     case AggregateFuncTypeEnum.GroupProperty: 
      newProjection = Projections.GroupProperty(p.Path); 
      goupprojections.Add(Projections.GroupProperty(p.Path), p.Name); 
      break; 
     case AggregateFuncTypeEnum.Sum: 
      newProjection = Projections.Sum(p.Path); 
      break; 
     default: 
      newProjection = Projections.Property(p.Path); 
      break; 
    } 
    projections.Add(newProjection, p.Name); 
} 
criteria.SetProjection(projections).SetResultTransformer(new AliasToBeanResultTransformer(projectionType)); 

if (goupprojections.Aliases.Length == 0) 
{ 
    rowcount.SetProjection(Projections.RowCount()) 
} 
else 
{ 
    rowcount.SetProjection(Projections.Count(goupprojections)) 
} 

var results = criteria.Future(); 
var count = rowcount.FutureValue<int>(); 
+0

這似乎仍然返回例如計數100而不是由投影返回的20行(例如,按'代碼'分組並且總和爲'成本') – Adam

+0

'rowcount.SetProjection(Projections.Count(goupprojections))'應該做imo,我會檢查至少在 – Firo

+0

看起來應該但不適合我。使用你的想法,我可以選擇一個屬性來使用CountDistinct進行分組,但這隻接受一個屬性 – Adam