C# 如何计算EF中每个产品的产品总数

C# 如何计算EF中每个产品的产品总数,c#,entity-framework,C#,Entity Framework,我有两张桌子放这个箱子。 我想为这段代码中的每个产品带来产品的总数量(sum(ProductNumber)),但我不知道具体数量 CimriContext context = new CimriContext(); public ICollection<StockDto.StockHeader> FillDataGrid(int userCompanyId) { return context.Stocks.Where(s => s.UserCo

我有两张桌子放这个箱子。

我想为这段代码中的每个产品带来产品的总数量(sum(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();
    }
CimriContext上下文=新的CimriContext();
公共ICollection FillDataGrid(int userCompanyId)
{
返回context.Stocks.Where(s=>s.UserCompany.UserCompanyId.Equals(UserCompanyId))。
选择(s=>newstockdto.StockHeader()
{
StockId=s.StockId,
StockName=s.StockName,
工件=//我怎么能在这里?
}).ToList();
}

您可以根据所需的位置获取产品列表,然后像下面这样使用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();

您可以根据所需的位置获得产品列表,然后像下面这样使用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();

您需要在
productTransaction
集合中找到所有匹配的记录,然后对
ProductNumber
进行求和

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

您需要在
productTransaction
集合中找到所有匹配的记录,然后对
ProductNumber
进行求和

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

因此,我假设
product_stockid
stockid
的外键?@Aominè是的,您的评论是正确的,因此我假设
product_stockid
stockid
的外键?@Aominè是的,您的评论是正确的