Entity framework Linq to实体多对多返回嵌套对象
如果我有三个多对多关系表,包括连接表、学生、学生课程、课程: 如何返回学生对象及其关联的课程对象 为了进一步澄清,以下是学生视图模型:Entity framework Linq to实体多对多返回嵌套对象,entity-framework,linq-to-entities,many-to-many,Entity Framework,Linq To Entities,Many To Many,如果我有三个多对多关系表,包括连接表、学生、学生课程、课程: 如何返回学生对象及其关联的课程对象 为了进一步澄清,以下是学生视图模型: public class StudentViewModel { public int StudentID { get; set; } public string Title { get; set; } public string Name { get; set; } ... ... ... public I
public class StudentViewModel
{
public int StudentID { get; set; }
public string Title { get; set; }
public string Name { get; set; }
...
...
...
public ICollection<StudentCourseViewModel> StudentCourses { get; set; }
}
不幸的是,在调试student对象时的视图中,没有返回studentcourses。看看查询的语法,这是有意义的,因为它只返回学生
我试过投影,例如
var query = from student in context.Students
from studentcourse in student.StudentCourses
where studentcourse.CourseID == 4
select new
{
student,
StudentCourses = studentcourse
}
但是投影会重塑输出学生对象的形状,并且不符合学生形状(类型),因为我使用的是学生视图模型
以下是我的视图代码片段:
@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)
...
所以,在这一点上,我真的卡住了。我本以为这很简单,但我花了一整天的时间研究、尝试和错误。您可以使用
Include
强制加载相关实体:
var query = from student in context.Students
.Include("StudentCourses")
.Include("StudentCourses.Course")
where studentcourse.CourseID == 4
select student;
是的,谢谢。我可能会被迫使用Includes,因此结果类型与查询的类型相同,即Student。我希望避免使用include(由于潜在的性能问题),但我认为没有其他选择。投影会产生匿名类型,我现在看到我无法使用它,因为我无法将匿名类型传递给我的视图模型。
var query = from student in context.Students
.Include("StudentCourses")
.Include("StudentCourses.Course")
where studentcourse.CourseID == 4
select student;