如何使用sum函数与条件和isqull检查linq实体?

时间:2014-01-01 11:33:36

标签: c# sql linq join linq-to-entities

新年快乐...我正在与linq合作实体,并在这里受到了打击,

SELECT O.InvoiceId, O.CustID, O.PickupDate, O.OrderDate, O.OrderNumber, O.ProNumber, O.PO1, O.PO2,
O.BaseRATE,O.OrderTotal,O.DiscAmount,
O.NormalDiscount,
ISNULL((Select Sum(AccessorialChargeAmount) from OrderDriverExtraCharge where OrderNumber = O.OrderNumber),0) As AccCharge,
ISNULL((SELECT Sum(AccessorialChargeAmount) FROM AccessorialCharge INNER JOIN
OrderDriverExtraCharge ON AccessorialCharge.AccessorialChargeId = OrderDriverExtraCharge.AccessorialChargeId
WHERE (((AccessorialCharge.Taxable)=1) AND ((OrderDriverExtraCharge.OrderNumberId)=O.OrderNumberId))),0) As Taxable FROM [Order] O
WHERE (((O.InvoiceId)=@InvoiceId))
Order By OrderNumberId 

这是一个巨大的sql qry我必须将它转换为linq到实体查询。

我喜欢

 var qry = (from O in _uow.Orders.GetAll()
join OD in _uow.OrderDriverExtraCharge.GetAll() on O.OrderNumberId equals OD.OrderNumberId
let AC in _uow.AccessorialCharges.GetAll() on OD.AccessorialChargeId equals AC.AccessorialChargeId
where O.InvoiceId == InvoiceId
select new {

}); 

但不知道如何在where条件中使用sum函数,并且为null:(

特别是我对这部分感到困惑

ISNULL((SELECT Sum(AccessorialChargeAmount) FROM AccessorialCharge INNER JOIN
    OrderDriverExtraCharge ON AccessorialCharge.AccessorialChargeId = OrderDriverExtraCharge.AccessorialChargeId
    WHERE (((AccessorialCharge.Taxable)=1) AND ((OrderDriverExtraCharge.OrderNumberId)=O.OrderNumberId))),0) As Taxable FROM [Order] O
    WHERE (((O.InvoiceId)=@InvoiceId))
    Order By OrderNumberId 

不知道如何使用null与where和某些条件。

任何建议或任何相关的例子将不胜感激。如果它适合我​​,我会标记你的答案。提前致谢。新年快乐。

2 个答案:

答案 0 :(得分:1)

我认为你需要这样的东西

from O in _uow.Orders.GetAll()
where O.InvoiceId == InvoiceId
orderby O.OrderNumberId
let AccCharge = (from odec in _uow.OrderDriverExtraCharge.GetAll()
                 where odec.OrderNumber == O.OrderNumber
                 select odec.AccessorialChargeAmount
                ).Sum() ?? 0
let Taxable = (from ac in _uow.AccessorialCharge.GetAll()
               join odec in _uow.OrderDriverExtraCharge.GetAll() on ac.AccessorialChargeId equals odec.AccessorialChargeId
               where ac.Taxable == 1 &&//possibly this you use boolean
                     odec.OrderNumberId == O.OrderNumberId
              ).Sum() ?? 0
select new{
    O.InvoiceId, 
    O.CustID, 
    O.PickupDate, 
    O.OrderDate, 
    O.OrderNumber, 
    O.ProNumber, 
    O.PO1, 
    O.PO2,
    O.BaseRATE,
    O.OrderTotal,
    O.DiscAmount,
    O.NormalDiscount,
    AccCharge,
    Taxable 
}

答案 1 :(得分:0)

试试这个

 var qry = (from O in _uow.Orders.GetAll()
join OD in _uow.OrderDriverExtraCharge.GetAll() on O.OrderNumberId equals OD.OrderNumberId
let AC in _uow.AccessorialCharges.GetAll() on OD.AccessorialChargeId equals AC.AccessorialChargeId
where O.InvoiceId == InvoiceId
select new {

}).Sum(r => (decimal?) r.AccessorialCharges)