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

nHibernate - Adding aggregate functions in .select

我正在尝试在 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();

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

我尝试了很多东西并发现它有效

.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。只是给新人的提示。