我怎么能linq 3表

时间:2014-02-25 17:11:08

标签: linq entity-framework linq-to-entities

如何linq我可以将学生与学校联系起来的3个表格。表格是:Students, Depart, School.

studentId(pk), departId(fk) departId(pk), schoolId(fk) schoolId(pk)

下面是连接两个表

@foreach (var student in Model.students.Where(s => s.schoolId == item.schoolId)) 

2 个答案:

答案 0 :(得分:0)

你想要什么?你可以加入他们......

var query = (from depart in Model.Depart
             join school in Model.School on depart.departId equals school.departId
             join student in Model.students on school.schoolId equals student.schoolId
             where students.schoolId == item.schoolId
             select new
             {
                 depart,
                 school,
                 student
             });

...或

答案 1 :(得分:0)

如果您的关联正确配置,而不是连接,您也可以使用关联:

var query = from school in Model.Schools
            from dept in school.Departments
            from student in dept.Students
            select new { student, dept, school};