NHibernate ICritera子查询与父值合并

时间:2012-10-17 16:18:20

标签: nhibernate

我想从ICriteria生成以下sql

select   c.Id, 
       sum(c.Amount) Amount,
       (select COALESCE(max(AuditDate), c.WhenAdded) FROM Audit a WHERE c.Id = a.CId) StatusDate
from    c
join    l
on  c.Id = l.CId
Group By c.Id, c.WhenAdded

到目前为止我已经

ICriteria crit = CurrentSession.CreateCriteria<C>()
     .CreateAlias("L", "l")
     .SetProjection(Projections.ProjectionList()
     .Add(Projections.Group<C>(x => x.Id), "Id")
     .Add(Projections.Sum("l.Amount"), "Amount")
     .Add(Projections.SubQuery(DetachedCriteria.For<Audit>("ca")
        .SetProjection(Projections.ProjectionList().Add(
              Projections.SqlFunction("COALESCE", 
                NHibernateUtil.DateTime, 
                Projections.Max<ClaimAudit>(x=> x.AuditDate),
                Projections.Property<C>(x => x.WhenAdded)), "StatusDate"))))
     .SetResultTransformer(Transformers.AliasToBean<CDto>());

但我无法在子子查询的合并中获取父列。我得到以下异常

无法找到属性C.WhenAdded

我知道子查询在子查询中查找名为WhenAdded的列,但不确定如何告诉它在父查询中查找? 关于如何实现这一点的任何想法?

PS。我需要以这种收敛的方式做到这一点,否则我得到一个不正确的金额总和。所以没有建议在没有子查询的情况下重写,除非考虑到这一点。

感谢。

1 个答案:

答案 0 :(得分:1)

将coalesce从子查询中移出并使用别名来限制Adit条目

ICriteria crit = CurrentSession.CreateCriteria<C>("c")
     .CreateAlias("L", "l")
     .SetProjection(Projections.ProjectionList()
         .Add(Projections.Group<C>(x => x.Id), "Id")
         .Add(Projections.Group<C>(x => x.WhenAdded), "WhenAdded")
         .Add(Projections.Sum("l.Amount"), "Amount")
         .Add(Projections.SqlFunction("COALESCE", NHibernateUtil.DateTime, 
             Projections.SubQuery(DetachedCriteria.For<Audit>()
                 .Add(Restrictions.PropertyEq("C.Id", "c.Id")
                 .SetProjection(Projections.Max<ClaimAudit>(x=> x.AuditDate)),
             Projections.Property<C>(x => x.WhenAdded)), "StatusDate")))
     // AliasToBean !?
     .List();