如果我有多对多关系的表,包括联结表,学生,学生课程,课程:
如何返回带有相关课程对象的Student对象?
为了进一步说明,这是学生视图模型:
public class StudentViewModel
{
public int StudentID { get; set; }
public string Title { get; set; }
public string Name { get; set; }
...
...
...
public ICollection<StudentCourseViewModel> StudentCourses { get; set; }
}
以下Linq to Entities查询只返回学生对象,因此我的问题!
var query = from student in context.Students
from studentcourse in student.StudentCourses
where studentcourse.CourseID == 4
select student;
不幸的是,在我调试学生对象的视图中,没有返回学生课程。查看查询的语法,这是有道理的,因为它只返回学生。
我尝试过投影,例如
var query = from student in context.Students
from studentcourse in student.StudentCourses
where studentcourse.CourseID == 4
select new
{
student,
StudentCourses = studentcourse
}
但是投影重塑了输出Student对象,并且不符合学生形状(类型),因为我正在使用学生视图模型。
以下是我的观看代码片段:
@foreach (var item in Model)
{
@Html.DisplayFor(s => item.Name)
...
...
@foreach (var subItem in item.StudentCourses)
{
@Html.DisplayFor(sc => subItem.Description)
@Html.DisplayFor(c => subItem.Course.Name)
...
所以,真的停留在这一点上。我本以为这会很简单,但我花了整整一天研究,试验和错误。
答案 0 :(得分:1)
您可以使用Include
:
var query = from student in context.Students
.Include("StudentCourses")
.Include("StudentCourses.Course")
where studentcourse.CourseID == 4
select student;