Linq在列表的每个项目中包含属性

时间:2018-02-13 14:54:58

标签: c# linq

我有这4个班级。

它们在层次结构中使用:

  class Reception {
      virtual List<Pallets> Pallets { get; set; }
      float Weight { get; set; }
  }

  class Pallet {
      virtual List<PalletDetail> PalletDetail { get; set; }
  }

  class PalletDetail {
      virtual Package Package { get; set; }
      int Quantity { get; set; }
  }

  class Package {
      float Weight { get; set; }
  }

对于每次接待我想计算重量,所以我有这样的东西:

foreach (var reception in dbContext.Receptions
    .Include(a => a.Pallets)
    .Include(a => a.Pallets.Select(b => b.PalletDetail))
    .ToList())
{
    reception.Weight = reception.Pallets
                            .SelectMany(p => p.PalletDetail)
                            .Sum(r => r.Quantity * r.Package.Weight) ?? 0;
}

dbContext.SaveChanges();

问题是对象Package未包含在查询中,因此前一个foreach在每次迭代中都生成一个SQL查询

问题:我如何包含它? (语法是什么?)

1 个答案:

答案 0 :(得分:2)

您只需要包含该套件,将所有套件替换为一个套件:

var receptions = dbContext.Receptions
    .Include(r => r.Pallets
        .Select(p => p.PalletDetail
            .Select(pd => pd.Package)))
    .ToList());