2010-09-16 123 views
0

我有以下查詢HNibernate:有助於避免N + 1查詢

DetachedCriteria criteria = DetachedCriteria.For(typeof(Income)) 
       .CreateAlias("Product", "p") 
       .SetProjection(
        Projections.ProjectionList() 
         .Add(Projections.GroupProperty("Product")) 
         .Add(Projections.Sum("Quantity")) 
       ); 

其轉換爲SQL:

SELECT this_.Product_id as y0_, 
     sum(this_.Quantity) as y1_ 
FROM  income this_ 
     inner join products p1_ 
      on this_.Product_id = p1_.Id 
GROUP BY this_.Product_id 

我的域名:

class Product 
{ 
    IList<Income> Incomes {get;set;} 
} 

class Income 
{ 
    Product Product {get;set;} 
} 

迭代時返回的集合我對每個Product實體都有一個查詢。 如何在一個查詢中獲取所有集合?

+0

你可以嘗試使用SetFetchMode屬性嗎? http://nhprof.com/Learn/Alerts/SelectNPlusOne – rebelliard 2010-09-16 13:01:30

+0

已經嘗試過 - SetFetchMode(「p」,FetchMode.Join)沒有效果 – kilonet 2010-09-16 13:18:33

回答

0

我喜歡HQL該類型的查詢......

select i.Product, sum(i.Quantity) 
from Income i 
group by /*all product properties*/ 
0

你使用Enumerable而不是List執行查詢?