首页 > 解决方案 > 实体框架加入三个实体总和

问题描述

我有三个实体,如下所示:

 public class StockSymbol
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public double Price { get; set; }
        public double PreviousPrice { get; set; }
        public double YesterdayPrice { get; set; }
        public double Change { get; set; }
    }

    public class CustomerOrder
    {
        public int Id { get; set; }
        public int StockSymbolId { get; set; }
        public int CustomerId { get; set; }
        public int StockCount { get; set; }
        public DateTime OrderDate { get; set; }

        public Customer Customer { get; set; }
        public StockSymbol Stock { get; set; }
    }

    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public double Balance { get; set; }

        public List<CustomerOrder> Orders { get; set; }
    }

如您所见,每个客户可以有多个库存订单,每个库存都有自己的价格。我想计算每个客户的总股票价格。我怎样才能用 linq 或 EF 做到这一点?我想获得每个客户的总价格订单。

标签: entity-frameworklinqentity-framework-core

解决方案


dbContext.Customers
    .Select(c => new
        {
            Customer = c,
            TotalCost = c.Orders.Sum(co => co.StockCount * co.Stock.Price),
        });

推荐阅读