在 QueryOver 中
Posted
技术标签:
【中文标题】在 QueryOver 中【英文标题】:Having in QueryOver 【发布时间】:2011-06-25 10:01:06 【问题描述】:我们正在努力解决以下问题。我们选择的 ORM 解决方案是 NHibernate,我们想使用 QueryOver 样式编写查询。现在有一个新的难题要解决,我们想进行如下查询:
select sp.Id, SUM(p.PriceAmount), SUM(i.BruttoAmount) from SellerProfile sp
left join SellerProfile_Invoice spi on spi.SellerProfile = sp.Id
left join Invoice i on spi.Invoice = i.Id
left join SellerProfile_Payment spp on spp.SellerProfile = sp.Id
left join Payment p on spp.Payment = p.Id
where i.PaymentDate < '2011-07-12'
group by sp.Id
having SUM(ISNULL(p.PriceAmount,0)) - SUM(ISNULL(i.BruttoAmount,0)) < 0
所以我们写了这样的代码:
Invoice invoice = null;
Payment payment = null;
SellerProfile seller = null;
var sellerIds = Session.QueryOver<SellerProfile>(() => seller)
.Left.JoinQueryOver(() => seller.Payments, () => payment)
.Left.JoinQueryOver(() => seller.Invoices, () => invoice)
.Where(() => invoice.PaymentDate < DateTime.Now - timeSpan)
.Select(Projections.Group(() => seller.Id))
.Where(Restrictions.Lt(new ArithmeticOperatorProjection("-", NHibernateUtil.Decimal, Projections.Sum(() => payment.Price.Amount), Projections.Sum(() => invoice.Brutto.Amount)), 0)).List<int>();
生成的 SQL 如下所示:
SELECT this_.Id as y0_
FROM SellerProfile this_ inner join ResourceOwner this_1_ on this_.Id=this_1_.Id
inner join Resource this_2_ on this_.Id=this_2_.Id
left outer join SellerProfile_Payment payments4_ on this_.Id=payments4_.SellerProfile
left outer join Payment payment2_ on payments4_.Payment=payment2_.Id
left outer join SellerProfile_Invoice invoices6_ on this_.Id=invoices6_.SellerProfile
left outer join Invoice invoice1_ on invoices6_.Invoice=invoice1_.Id
WHERE invoice1_.PaymentDate < @p0
and (sum(payment2_.PriceAmount) - sum(invoice1_.BruttoAmount)) < @p1
GROUP BY this_.Id
但是它抛出了一个异常,因为它将and
子句放在最后一行的第一个where
而不是having
并且我们的SQL 不起作用...
有什么帮助吗?谢谢...
【问题讨论】:
哪个数据库以及生成的查询是什么? 数据库是SQL Server...看我的帖子,我已经添加了生成的SQL... 【参考方案1】:AFAIK QueryOver、LINQ 和 Criteria API 不支持 HAVING 子句逻辑 (NH 3.1)
你可以使用 HQL。
HQL Examples
【讨论】:
以上是关于在 QueryOver 中的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Nhibernate 中对子集合进行 QueryOver