【问题标题】:SUM of Product of 2 Columns + the Product of another two columns in Entity Framework Navigation Properties实体框架导航属性中 2 列乘积的总和 + 其他两列的乘积
【发布时间】:2020-03-02 09:21:31
【问题描述】:

我正在尝试编写一个语句来获取实体框架中产品两个字段的总和。

给定以下结构:

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

但是这个版本确实得到了正确的总数。这个数字远低于预期。

【问题讨论】:

  • EF 的查询由于汇总这些行的方式而变为空值。

标签: c# asp.net-mvc-5 entity-framework-6 linq-to-entities


【解决方案1】:

所以这里的问题是 EF 为没有任何 ServiceLines 的任何订单获取空值,而不是添加零。

这两个选项都有效:

 .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 匿名对象的 DefaultIfEmpty 值,否则会用 null 搞砸加法。所以 EF 会得到 OrderLineTotal (value) + ServiceLineTotal (NULL) = NULL。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多