[英]How can I load a property of a navigational property?
I'm attempting to create a query using eager loading of navigational properties. 我正在尝试使用急切加载的导航属性来创建查询。 Is there a way to load a property of a navigational property?
有没有办法加载导航属性的属性? I get a 'sequence contains no element' exception when I try the code below.
当我尝试以下代码时,出现“序列不包含任何元素”异常。
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;
However when I use: 但是,当我使用:
viewModel.Enrollments = viewModel.Courses.Where(x => x.CourseID == courseID).Single().Enrollments;
it populates my viewModel.Enrollment property just fine. 它会很好地填充我的viewModel.Enrollment属性。 Is there a way to access this type of complex property in a linq query?
有没有办法在linq查询中访问这种类型的复杂属性?
Is there a way to load a property of a navigational property?
有没有办法加载导航属性的属性?
Looks like you know how to eager load multiple levels already: 您似乎已经知道如何渴望加载多个级别:
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);
This is where you are probably getting the exception (or possibly your other use of .Single()
): 这是您可能会得到异常的地方(或者可能是对
.Single()
其他使用):
viewModel.Enrollments = viewModel.Courses
.Where(x => x.CourseID == courseID)
.Where( e=>e.Enrollments.First().InstructorFullName == "Kim Abercrombie")
.Single().Enrollments;
From the docs for .Single()
来自
.Single()
的文档
Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence.
返回序列中的唯一元素,如果序列中不存在一个元素,则引发异常。
Here is how I solved it. 这是我解决的方法。 var selectTemp = viewModel.Courses.Where(x => x.CourseID == courseID).Single().Enrollments;
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.