2011-09-10 45 views
0
做以下的實體框架4.1

Following is the data model如何使用LINQ

假設上面給出的數據模型,如何在EF 4.1

Select 
    students.firstname 
    ,students.lastname 
    ,classes.classname 
    ,IsNull(studentsclasses.id,0) Attending 
from students 
cross join classes 
left outer join studentsclasses on studentsclasses.classid = classes.classid 
      and studentsclasses.studentid = students.studentid 
where students.studentid = 5 

下執行下面的查詢是我嘗試

from s in Students 
from c in Classes 
select new { 
       StudentFirstName = s.Firstname, 
       StudentLastName = s.Lastname, 
       ClassName = c.Classname 
      } 

回答

3

在實體框架中,studentsclasses之間的關係應該由導航屬性classes每個student包含學生所關聯的所有類的實體。使用這個你可以這樣做:

var student = Students.FirstOrDefault(s = > s.studentid == 5); 
if(student!=null) 
{ 
    var studentClasses = student.classes.Select(c => new 
    { 
    StudentFirstName = student.Firstname, 
    StudentLastName = student.Lastname, 
    ClassName= c.Classname  
    }); 
    //.. 
} 
+0

問題是第三列我能夠在兩個類上進行連接。但是,在EF 4.1中,你沒有中級課程。所以,我無法獲得第三欄的價值。 – Mohit

+0

@Mohit:你指的是第3列? – BrokenGlass

+0

我很抱歉第四列。看看下面的查詢 選擇 students.firstname ,students.lastname ,classes.classname ,ISNULL(studentsclasses.id,0)學生參加 交叉連接類 左外連接上studentsclasses.classid =類studentsclasses .classid and studentsclasses.studentid = students.studentid where students.studentid = 5 – Mohit