2011-12-18 55 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时。