HNibernate:有助于避免N + 1查询

时间:2010-09-16 08:20:11

标签: nhibernate

我有以下查询

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实体都有一个查询。 如何在一个查询中获取所有集合?

2 个答案:

答案 0 :(得分:0)

我更喜欢HQL用于那种查询......

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

答案 1 :(得分:0)

您是否使用Enumerable代替List来执行查询?