实体框架多对多关系

时间:2014-03-10 11:59:54

标签: entity-framework linq-to-entities

我正试图找到一种方法来制作一组实体(类似这样):

Students:

| StudentID |   Name    |
-------------------------
|    1      |    Joe    |
|    2      |   Jack    |


StudentsCourses:

| StudentID |  CourseID |
-------------------------
|    1      |    1      |
|    2      |    1      |
|    2      |    2      |


Courses:

|  CourseID |    Name     |
---------------------------
|    1      |   Math I    |
|    2      |   Math II   |

进入IEnumerable:

class StudentDTO
{
    public int ID {get; set;}
    public string Name {get; set;}
    public List<CourseDTO> Courses {get; set;}
}

class CourseDTO
{
    public int ID {get; set;}
    public string Name {get; set;}
}

在C#中使用Linq和EF。我一直在看GroupBy()方法,但我看不出如何使它“适合”我的需求。任何提示或建议将不胜感激。

到目前为止,我有以下问题:

var result = from s in db.Students
             from sc in db.StudentsCourses.Where(x => x.StudentID == sc.StudentID)
             from c in db.Courses.Where(x => x.CourseID == sc.CourseID)
             select new StudentDTO()
             {
                 ID = s.StudentID,
                 Name = s.Name
                 Courses = ???
             };

如何列出每个学生的所有课程?

1 个答案:

答案 0 :(得分:0)

您应该将两个from移到select

from s in db.Students
select new StudentDTO()
{
    ID = s.StudentID,
    Name = s.Name
    Courses = from sc in db.StudentsCourses
                           .Where(x => x.StudentID == s.StudentID)
              from c in db.Courses.Where(x => x.CourseID == sc.CourseID)
              select new CourseDto { ID = c.ID, Name = c.Name  }
};

但是,建议您在班级中使用导航属性:至少Student.StudentCoursesStudentCourse.Course。所以你可以这样做:

from s in db.Students
select new StudentDTO()
{
    ID = s.StudentID,
    Name = s.Name
    Courses = from sc i s.StudentsCourses
              select new CourseDto { ID = sc.Course.ID,
                                     Name = sc.Course.Name
                                   }
};