首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >实体框架导航属性中2列的乘积之和+另外两列的乘积

实体框架导航属性中2列的乘积之和+另外两列的乘积
EN

Stack Overflow用户
提问于 2019-11-06 07:16:25
回答 1查看 66关注 0票数 0

我正在尝试编写一条语句来获取Entity Framework中两个字段的乘积和。

给定以下结构:

代码语言:javascript
运行
复制
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;}
}

我尝试在一个查询中返回总订单值:

代码语言:javascript
运行
复制
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));

然而,这个版本没有得到正确的总数。这个数字比预期要少得多。

EN

回答 1

Stack Overflow用户

发布于 2019-11-06 09:18:50

所以这里的问题是,对于任何没有任何ServiceLines的订单,EF都会得到一个空值,而不是添加零。

这两个选项都有效:

代码语言:javascript
运行
复制
 .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) 
                );

代码语言:javascript
运行
复制
.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。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58720879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档