0

我想从 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 的列,但不确定如何告诉它在父查询中查找?关于如何实现这一目标的任何想法?

附言。我需要以这种复杂的方式执行此操作,否则我会得到不正确的金额。因此,除非考虑到这一点,否则没有建议在没有子查询的情况下重新编写。

谢谢。

4

1 回答 1

1

将合并从子查询中移出并使用别名来限制 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();
于 2012-10-18T10:06:24.400 回答