2014-01-25 32 views
1

我首先使用了EF6代碼,並且使用了MVC 5.我有兩個彼此具有多對多關係的模型類。 EF還爲我生成了包含學生和課程表的外鍵的聯結表。如何檢索同Linq的多對多關係的同學

public class Student 
{ 
    public int StudentId { get; set; } 
    public string Name { get; set; } 
    public ICollection<Course> Courses { get; set; } 
} 

public class Course 
{ 
    public int CourseId { get; set; } 
    public string Title { get; set; } 
    public ICollection<Student> Students { get; set; } 
} 

對於「學生A」,我想列出他在同一課程或同一課程中註冊爲「學生A」的同學。如果學生在「課程A」和「課程B」中註冊,在我的「操作」方法中,如何獲得在「課程A」和「課程B」中從StudentId註冊的學生列表?

我搜索了很多,但找不到任何具體的答案。任何幫助都會很棒。

回答

1

在普通的SQL,這可以通過交叉與本身加入結表來完成,然後過濾結果行:

select distinct sc2.[StudentId] 
from StudentsCourses sc1 
cross join StudentsCourses sc2 
where sc1.[StudentId] = 12345 and sc1.[CourseId] = sc2.[CourseId] 

實體框架並沒有給進入StudentsCourses表,但你可以嘗試效仿這種交叉使用下面的C#代碼加入:

from sc1 in (db.Students.SelectMany(s1 => s1.Courses.Select(c1 => new { Student = s1, Course = c1 }))) 
from sc2 in (db.Students.SelectMany(s2 => s2.Courses.Select(c2 => new { Student = s2, Course = c2 }))) 
where sc1.Student.StudentId == 12345 && sc1.Course.CourseId == sc2.Course.CourseId 
select sc2.Student; 

但我不知道是否EF將有效地生成SQL,所以你應該使用SQL事件探查器檢查。可能的話,對字符串使用ExecuteQuery方法會更好。

+0

非常感謝Vorrtex爲我工作。我會用分析器檢查它,看看它是如何去的。再次感謝:) – Mansoor