我正在尝试使用热切的导航属性加载来创建查询。有没有办法加载导航属性的属性?当我尝试下面的代码时,我得到一个'序列包含无元素'异常。
var viewModel = new InstructorIndexData();
viewModel.Instructors = db.Instructors.Include(i => i.OfficeAssignment)
.Include(i=>i.Assignments)
.Include(i => i.Students)
.Include (i=>i.Enrollments )
.Include(i => i.Courses.Select(c => c.Department))
.OrderBy(i => i.LastName);
viewModel.Courses = viewModel.Instructors.Where(i => i.InstructorID == id).Single().Courses;
viewModel.Enrollments = viewModel.Courses.Where(x => x.CourseID == courseID).Where( e=>e.Enrollments.First().InstructorFullName == "Kim Abercrombie").Single().Enrollments;
但是当我使用时:
viewModel.Enrollments = viewModel.Courses.Where(x => x.CourseID == courseID).Single().Enrollments;
它填充了我的viewModel.Enrollment属性就好了。有没有办法在linq查询中访问这种类型的复杂属性?
答案 0 :(得分:0)
有没有办法加载导航属性的属性?
看起来您已经知道如何急切加载多个级别:
viewModel.Instructors = db.Instructors.Include(i => i.OfficeAssignment)
.Include(i=>i.Assignments)
.Include(i => i.Students)
.Include (i=>i.Enrollments )
.Include(i => i.Courses.Select(c => c.Department))
.OrderBy(i => i.LastName);
这是您可能获得异常的地方(或者可能是您对.Single()
的其他用途):
viewModel.Enrollments = viewModel.Courses
.Where(x => x.CourseID == courseID)
.Where( e=>e.Enrollments.First().InstructorFullName == "Kim Abercrombie")
.Single().Enrollments;
来自.Single()
的{{3}}
返回序列的唯一元素,如果出现异常则抛出异常 序列中没有一个元素。
答案 1 :(得分:0)
以下是我如何解决它。 var selectTemp = viewModel.Courses.Where(x => x.CourseID == courseID).Single()。Enrollments;
var selectedTeacher = from t in selectTemp where t.InstructorFullName == teacher select t;
viewModel.Enrollments = selectedTeacher;