使用嵌套EF查询计算产品数量

时间:2017-12-04 13:18:59

标签: c# winforms entity-framework

我想计算每件商品的数量。我想为此使用这些表。

My Tables

我想要得到这样的结果。

StockId | StockName | Sum(ProductNumber)[实际产品数量]

我尝试使用此代码可以获取正确的结果但是它返回null值,即使它是满足条件的条件。

CimriContext context = new CimriContext();
    public ICollection<StockDto.StockHeader> FillDataGrid(int userCompanyId)
    {
        ICollection<StockDto.StockHeader> Stocks = context.Stocks.Where(c => c.UserCompanyId==userCompanyId).
             Select(c => new StockDto.StockHeader()
             {
                 StockId = c.StockId,
                 StockName = c.StockName,
                 Piece=0
             }).ToList();

        ICollection<StockDto.StockHeader> ProductHeader = new List<StockDto.StockHeader>();
        foreach (var products in Stocks)
        {
            products.Piece = context.ProductTransactions.Where(p => p.StockId==products.StockId).Sum(s => s.ProductNumber);
            ProductHeader.Add(products);
        }

        return ProductHeader.ToList();
    }

1 个答案:

答案 0 :(得分:0)

您想为每个库存记录检索ProductCount。您可以通过加入两个表并将StockIdStockNumber分组来执行此操作;

        var query = from stocks in context.Stocks 
                    join products in context.ProductTransactions ON stocks.StockId equals products.StockId
                    where stocks.UserCompanyId = userCompanyId
                    group stocks by new
                    {
                        stocks.StockId,
                        stocks.StockName
                    } into gcs
                    select new
                    {
                        StockId = gcs.Key.StockId,
                        StockName = gcs.Key.StockName,
                        ProductCounts = gcs.Count()
                    };