我有一个父子关系模型。 Year
和Week
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;
答案 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();