将多个结果分组到ViewModel中

时间:2014-08-27 20:07:12

标签: c# asp.net-mvc stored-procedures

这是我的情景。我有3个型号。我应该如何将ProductItems分组到每个ProductPack中。存储过程最好吗?如果是这样,它看起来像什么?我是存储过程的新手。我不知道如何让Entity框架将ProductItems添加到ProductPacks中。我正在使用ProductPackGroups表,因为我需要一种方法来保持我的产品包足够灵活,以便将现有的ProductItems混合和匹配到ProductPacks中。

ProductItems - ID - 标题 - 说明

ProductPacks - ID - 标题 - 说明

ProductPackGroups - ID - ProductItemId - ProductPackId - ProductItem - ProductPack

我运行我的IQueryable GetAllProductPackGroups(); 每个结果都包含一个ProductItem对象和ProductPack对象。

结果看起来像这样:

{Id = 1,ProductItemId = 1 ,ProductPackId = 1,ProductItem = [Object],ProductPack = [Object]} {Id = 1,ProductItemId = 2 ,ProductPackId = 1,ProductItem = [Object],ProductPack = [Object]} {Id = 1,ProductItemId = 3 ,ProductPackId = 1,ProductItem = [Object],ProductPack = [Object]} {Id = 1,ProductItemId = 4 ,ProductPackId = 1,ProductItem = [Object],ProductPack = [Object]} {Id = 1,ProductItemId = 5 ,ProductPackId = 1,ProductItem = [Object],ProductPack = [Object]}

1 个答案:

答案 0 :(得分:0)

您可以利用EF的热切提取来最小化数据库调用次数。这样的事情可以解决问题:

var productPackGroups = _dbContext.ProductPackGroups
                                  .Include(x => x.ProductPacks)
                                  .Include(x => x.Products);

MSDN在EF中加载相关实体的方式有really good article

相关问题