具有左外连接的复杂NHibernate标准?

时间:2012-04-17 22:15:15

标签: nhibernate subquery left-join

我对NHibernate很新。我使用CreateSQLQuery编写了这个,但是如果可能的话我想把它移到NHibernate Criteria格式。我的查询如下:

select parent.ID as Id, ValueA.Total as ValueACount, ValueB.Total as ValueBCount
from ParentTable parent 
left outer join
(
  select count(*) as Total, ID 
  from ChildTable
  where state = 'ValueA' 
  group by ID
) ValueA on ValueA.ID = parent.ID
left outer join
(
  select count(*) as Total, ID
  from ChildTable
  where state = 'ValueB' 
  group by ID
) ValueB on ValueB.ID = parent.ID

我更改了表名/值以抽象它。代码按原样工作,但这是我们在整个解决方案中唯一的查询。我想看看我们是否可以摆脱它。

提前感谢所有可以提供帮助的人。如果你想给我一个非常好的网页链接,可以帮助我,那也没关系。我至少会翻阅你:)

我也看到过类似的问题。如果您觉得其他一些问题/答案对我有很大的帮助,请随时指出。

1 个答案:

答案 0 :(得分:2)

你可以尝试一些linq fu

var results = from p in session.Query<Parent>()
              select new
              {
                  p.Id,
                  ValueACount = (from c1 in session.Query<Child>() where c1.State == "ValueA" && c1.Parent == p select c1).Count(),
                  ValueBCount = (from c2 in session.Query<Child>() where c2.State == "ValueB" && c2.Parent == p select c2).Count(),
              };

或使用标准

var results = session.CreateCriteria<Parent>("p")
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.Property("Id"))
        .Add(Projections.SubQuery(DetachedCriteria.For<Child>()
            .Add(Restrictions.Eq("State", "ValueA") && Restrictions.EqProperty("Parent", "p"))
            .SetProjection(Projections.RowCount())))
        .Add(Projections.SubQuery(DetachedCriteria.For<Child>()
            .Add(Restrictions.Eq("State", "ValueB") && Restrictions.EqProperty("Parent", "p"))
            .SetProjection(Projections.RowCount()))))
    .List();