如何根据商店获得产品数量

时间:2016-05-11 10:58:04

标签: c# entity-framework

我有三张表:ProductStoreDetailStore Store表格包含storeName。 我想根据storeName获取产品数量,为此我使用下面的代码:

 var stocksQuery = storeDetails.GroupBy(row => new { row.StoreId, row.ProductId }).AsQueryable();

        List<StockStatusViewModel> result = new List<StockStatusViewModel>();
        foreach (var item in stocksQuery)
        {
            result.Add(new StockStatusViewModel
            {
                Quantity = item.Sum(row => row.Quantity),
                ProductCombinationId = item.Key.ProductAttributeCombinationId,
                StoreId = item.Key.StoreId,
                // here I need productName and StoreName
            });

        }

但是我需要storeName和ProductName,我怎么能得到这些? 这是我的课程:

 public class StoreDetail 
{
    public Product Product{ get; set; }
    public  Guid ProductId { get; set; }
 }

 public class Product{
 public  ICollection<StoreDetail> StoreDetails { get; set; }
    }

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情,而不是按 StoredId ProductId 进行分组,我会按商店产品进行分组

var stocksQuery = storeDetails.GroupBy(row => new { row.Store, row.Product }).AsQueryable();

        List<StockStatusViewModel> result = new List<StockStatusViewModel>();
        foreach (var item in stocksQuery)
        {
            result.Add(new StockStatusViewModel
            {
                Quantity = item.Sum(row => row.Quantity),
                ProductCombinationId = item.Key.ProductAttributeCombinationId,
                StoreId = item.Key.StoreId,
                StoreName = item.Key.Store.StoreName,
                ProductName = item.Key.Product.ProductName
            });

        }

为了获得更好的性能,我认为我们只需选择我们需要的内容,以便将代码更改为

var stocksQuery = storeDetails.GroupBy(row => new { row.StoreId, row.Store.StoreName, row.ProductId, row.Product.ProductName }).AsQueryable();

            List<StockStatusViewModel> result = new List<StockStatusViewModel>();
            foreach (var item in stocksQuery)
            {
                result.Add(new StockStatusViewModel
                {
                    Quantity = item.Sum(row => row.Quantity),
                    ProductCombinationId = item.Key.ProductAttributeCombinationId,
                    StoreId = item.Key.StoreId,
                    StoreName = item.Key.StoreName,
                    ProductName = item.Key.ProductName
                });

            }