nHibernate - 在.select中添加聚合函数

时间:2015-04-06 19:32:58

标签: nhibernate aggregate-functions queryover

我正在尝试在QueryOver中实现商业公式。

POorder.Estimate是一个计算字段,我需要

ToDateOrderAmount = POrder.Estimate - Sum(PODist.Field1) - Sum(PODisTaxRebate.Field1 + PODisTaxRebate.Field2)

所以我需要编写一个查询。我现在拥有的是:

    var reportModels =
        Session.QueryOver<Domain.Model.Purchasing.Vendor>(() => v)
            .Left.JoinQueryOver(() => v.Invoices, () => invoice)
            .Left.JoinQueryOver(() => invoice.PurchaseOrder, () => poOrder)
            .Left.JoinQueryOver(() => poOrder.PurchaseOrderDistributions, () => poDistribution)
            .Left.JoinQueryOver(() => poDistribution.TaxRebate, () => poTaxRebate)
            .SelectList(
                list =>
                list.Select(() => v.Number).WithAlias(() => varptModel.VendorNumber)
                    .Select(() => v.TypeCode.Code).WithAlias(() => varptModel.VendorType)
                    .Select(() => v.Name).WithAlias(() => varptModel.VendorName)
                    .Select(() => v.PurchasingContactPhoneNumber + "-Ext." + v.PurchasingContactPhoneNumberExt).WithAlias(() => varptModel.Phone)
                    .Select(() => v.Address).WithAlias(() => varptModel.Address)
                    .Select(() => invFiscalYear.Year).WithAlias(() => varptModel.Year)
                    .Select(() => invoice.TotalAmount).WithAlias(() => varptModel.InvoiceToDate)
                    .Select(() => invoice.AmountPaidToDate).WithAlias(() => varptModel.PaymentToDate)
                    .Select(() => poOrder.Estimate).WithAlias(() => varptModel.OrdersToDate)
        .Select(() => poOrder.Estimate - Sum(poDistribution.Field1) - Sum(poTaxRebate.Discount1 + poTaxRebate.Discount2) )
                    ).List();

但这不对。我应该把它改成什么?

1 个答案:

答案 0 :(得分:2)

我尝试了很多东西,发现这个工作

.Select(Projections.SqlFunction(new VarArgsSQLFunction("", "+", ""),
                                NHibernateUtil.Double,
                                Projections.SqlFunction(new VarArgsSQLFunction("", "+", ""),
                                NHibernateUtil.Double,
                                Projections.Sum(Projections.SqlFunction("coalesce", NHibernateUtil.Double, Projections.Property(() => invoiceLineItem.Expense), Projections.Constant(0))),
                                Projections.Sum(Projections.SqlFunction("coalesce", NHibernateUtil.Double, Projections.Property(() => invitemTaxRebate.Rebate1Expense), Projections.Constant(0)))),
                                Projections.Sum(Projections.SqlFunction("coalesce", NHibernateUtil.Double, Projections.Property(() => invitemTaxRebate.Rebate2Expense), Projections.Constant(0)))))
                                .WithAlias(() => varptModel.ToDateInvoices)

在SQL中给了我这个

sum(coalesce(invoicelin8_.Expense, 0 )) + sum(coalesce(invitemtax9_.Rebate1Expense, 0 )) + sum(coalesce(invitemtax9_.Rebate2Expense, 0 )) 

我添加了Coalesce,因为当我们使用null值添加或减去值时,所有值在结果中都为null。只是暗示新的。