我有三张表:Product
和StoreDetail
,Store
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; }
}
答案 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
});
}