0

我正在尝试使用急切加载导航属性来创建查询。有没有办法加载导航属性的属性?当我尝试下面的代码时,我得到一个“序列不包含元素”异常。

       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 查询中访问这种类型的复杂属性?

4

2 回答 2

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()

返回序列的唯一元素,如果序列中不完全有一个元素,则抛出异常。

于 2013-03-19T09:19:46.530 回答
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;
于 2013-03-23T06:46:09.017 回答