Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement in operator in Entity Framework

I try to implement this SQL query in Entity Framework

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

I guess this is an approach:

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

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

but this is not working!

Has anyone else tried to do something like this?

like image 978
Mohammad Abbasi Avatar asked Jul 28 '13 07:07

Mohammad Abbasi


1 Answers

A SQL IN is equivalent to a LINQ Contains.

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

So, the SQL statement:

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

is Equivalent in LINQ to:

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;
like image 141
R.C Avatar answered Nov 11 '22 12:11

R.C