2011-12-18 112 views
2

我有三個實體,如下所示。將LINQ轉換爲實體不包含到Lambda表達式中

Student { StudentID, Name, Age } 

Parent { ParentID, Name, Age } 

StudentParent { StudentParentID, StudentID, ParentID } 

我需要得到一個IQueryable列表的學生是一定年齡,沒有父母。我目前正在使用下面的代碼工作。

IQueryable<Student> Student s = from s in db.Students 
           where s.Age == 18 
           where !(from sp in db.StudentParent where sp.StudentID == s.StudentID select sp.StudentID).Contains(s.StudentID) 
           select s; 

我只想幫助將其轉換爲Lambda表達式。

+0

有一個類似的問題,有人問了一下:http://stackoverflow.com/questions/3739246/linq-to-sql-not-contains-or-not-in。答案比迄今爲止的答案更簡潔一些。 – 2011-12-18 02:54:43

回答

2

這應該工作:

db.Students.Where(s => 
    s.Age == 18 && db.StudentParent.All(sp => sp.StudentID != s.StudentID) 
); 

編輯:這裏假設你沒有從學生到家長的鏈接;如果你這樣做,使用它來代替連接,以提高可讀性。

+0

這工作,我只做了小改動再次感謝db.Students.Where(s => s.Age == 18 && s.StudentParent.All(sp => sp.StudentID!= s.StudentID) ); – 2011-12-18 06:03:25

4

您應該在實體模型中創建關聯。

然後,您可以編寫

db.Students.Where(s => s.Age == 18 && s.Parents.Count == 0) 

你應該永遠不需要專門查詢連接表(如您的StudentParent)使用ORM時。