如何计算EF中λ值的每种产品的总产品

时间:2017-11-11 23:39:27

标签: c# entity-framework

这个案子我有两张桌子。 enter image description here

我想在此代码中为每件产品带来总产品(总和(ProductNumber)),但我不知道件。

CimriContext context = new CimriContext();
    public ICollection<StockDto.StockHeader> FillDataGrid(int userCompanyId)
    {
        return context.Stocks.Where(s => s.UserCompany.UserCompanyId.Equals(userCompanyId)).
            Select(s => new StockDto.StockHeader()
            {
                StockId = s.StockId,
                StockName = s.StockName,
                Piece = // how can I here ?
            }).ToList();
    }

2 个答案:

答案 0 :(得分:0)

你可以根据你想要的地方获得产品清单,然后像这样使用linq sum

var productsList = context.Products.Where(
       s =>s.UserCompany.UserCompanyId.Equals(userCompanyId)).ToList();

 var totalOfPiece = productsList.sum(m=>m.Piece) 
//or replace Piece with int value 

    return context.Stocks.Where(s => s.UserCompany.UserCompanyId.Equals(userCompanyId)).
                Select(s => new StockDto.StockHeader()
                {
                    StockId = s.StockId,
                    StockName = s.StockName,
                    Piece = totalOfPiece // total of Pieces here 
                }).ToList();

答案 1 :(得分:0)

您需要在productTransaction集合中找到所有匹配的记录,然后执行ProductNumber的总和。

 Piece = context.ProductTransactions.Where(x => x.product_stockid == s.stockId)
                                    .Sum(x => x.ProductNumber);