2015-04-06 95 views
0

我試圖在QueryOver中實現一個商業公式。nHibernate - 在.select中添加聚合函數

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(); 

但是這是不對的。我應該怎樣改變它?

+0

你想要生成什麼SQL? –

+0

首先很高興看到你,因爲我在一個月前從你的博客或網站開始學習nHibernate。在這裏,我試圖在QueryOver中實現一個業務公式。 POorder.Estimate是需要獲取的計算字段ToDateOrderAmount = POrder.Estimate - Sum(PODist.Field1) - Sum(PODisTaxRebate.Field1 + PODisTaxRebate.Field2)。如果你想,那麼我可以發送整個查詢。 – Ammad

+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)) 

我加入合併,當我們加上或減去與空值值,所有的值變爲零結果。只是提示新的。