我正在尝试编写一条语句来获取Entity Framework中两个字段的乘积和。
给定以下结构:
public class Order
{
public int OrderNUmber {get; set;}
public virtual List<Orderline> OrderLines {get; set;}
public virtual List<ServiceLine> ServiceLines {get; set;}
public string someproperty {get; set;}
}
public class OrderLine
{
public string productname {get; set;}
public int quantity {get; set;}
public decimal price {get; set;}
}
public class ServiceLine
{
public string servicename {get; set;}
public int quantity {get; set;}
public decimal rate {get; set;}
}我尝试在一个查询中返回总订单值:
var GrandTotal = Orders.Where(q => q.someproperty == "somecondition")
.Sum(order =>
order.OrderLines.Sum(line => line.quantity * line.price)
+ order.ServiceLines.Sum(sl =>sl.quantity * sl.rate));然而,这个版本没有得到正确的总数。这个数字比预期要少得多。
发布于 2019-11-06 09:18:50
所以这里的问题是,对于任何没有任何ServiceLines的订单,EF都会得到一个空值,而不是添加零。
这两个选项都有效:
.Sum(
order =>
order.OrderLines.Select(n => new{n.quantity, n.price}).DefaultIfEmpty(new {quantity = 0, price = decimal.Zero}).Sum(line => line.quantity * line.price) + order.ServiceLines.Select(n => new{n.quantity, n.rate}).DefaultIfEmpty(new {quantity = 0, rate = decimal.Zero}).Sum(acl =>acl.quantity * acl.rate)
);和
.Sum(
order =>
order.OrderLines.Select(lines => new { LineTotal = lines.quantity * lines.price }).DefaultIfEmpty(new { LineTotal = Decimal.Zero }).Sum(x => x.LineTotal) + order.ServiceLines.Select(acl => new { AclTotal = acl.quantity * acl.rate }).DefaultIfEmpty(new { AclTotal = Decimal.Zero }).Sum(x => x.AclTotal)
);有必要告诉EF匿名对象的null值,否则会搞砸与DefaultIfEmpty的加法。因此EF将得到OrderLineTotal (值)+ ServiceLineTotal ( NULL ) =NULL。
https://stackoverflow.com/questions/58720879
复制相似问题