如果我需要查找父ID,如何在单个查询中获取所有子记录?

时间:2018-04-25 17:52:12

标签: c# entity-framework linq

我有一个父子关系模型。 YearWeek

Years: YearID, Name
Weeks: WeekID, YearID, Name

所以,如果我有YearSelected,那么为了获得我一年中的所有周数:

List<Week> weeks = db.weeks.Where(w => w.YearID == model.YearSelected).ToList();
model.WeekList = new SelectList(weeks, "WeekID", "Name");

但在DB中我只保存WeekID,因此只有model.WeekSelected

那么我如何获得与model.WeekSelected

相同年份的所有一周

我可以先查询以获取YearID,但想知道是否可以在一行中完成。

int YearID = db.weeks.Where(w => w.WeekID == model.WeekSelected)
                     .SingleOrDefault().YearID.Value;

1 个答案:

答案 0 :(得分:1)

您需要使用子查询来获取YearID

List<Week> weeks = db.weeks
    .Where(w => w.YearID == db.weeks.First(w => w.WeekID == model.WeekSelected).YearID)
    .ToList();

当您知道WeekSelected只匹配一行时,这会产生更简单的SQL,不确定它是否会产生性能差异:

List<Week> weeks = db.weeks
    .Where(w => w.YearID == db.weeks.Single(w => w.WeekID == model.WeekSelected).YearID)
    .ToList();