2013-07-28 177 views
4

我嘗試在實體框架來實現這個SQL查詢實現實體框架

select * 
from students 
where student.fieldid in (select fieldid from fields where groupid = 10) 

我想這是一種方法:

var fields = context.fields.where(t=>t.groupid = 10).toList(); 

var result = context.students.where(t=> fields.Contains(t.fieldid)).toList(); 

,但是這是不工作!

有沒有其他人試圖做這樣的事情?

回答

5

SQL IN相當於LINQ Contains

var names = new string[] { "Alex", "Colin", "Danny", "Diego" };  
var matches = from person in people 
       where names.Contains(person.Firstname) 
       select person; 

因此,該SQL語句:

select * from students where student.fieldid in (select fieldid from fields 
where groupid = 10) 

是相當於在LINQ到:

var fieldIDs= from Fids in db.fields 
       where Fids.groupid==10 
       select Fids.fieldid; 

var results= from s in db.students 
      where fieldIDs.Contains(s.fieldid) 
      select s;