In Lambda :
var persons = Persons.Where(p=>(p.PersonLocations.Select(ps=>ps.Location)
.Where(l=>l.Description == "Amsterdam").Count() > 0)
&& (p.PersonRoles.Select(pr=>pr.Role)
.Where(r=>r.Description == "Student").Count() > 0));
query result:
SELECT [t0].[personId] AS [PersonId], [t0].[description] AS [Description]
FROM [Persons] AS [t0]
WHERE (((
SELECT COUNT(*)
FROM [personlocations] AS [t1]
INNER JOIN [Locations] AS [t2] ON [t2].[locationid] = [t1].[locationid]
WHERE ([t2].[description] = @p0) AND ([t1].[personid] = [t0].[personId])
)) > @p1) AND (((
SELECT COUNT(*)
FROM [PersonRoles] AS [t3]
INNER JOIN [Roles] AS [t4] ON [t4].[roleid] = [t3].[roleid]
WHERE ([t4].[description] = @p2) AND ([t3].[personid] = [t0].[personId])
)) > @p3)
Using Contains():
var persons = Persons
.Where(p=>(p.Personlocations.Select(ps=>ps.Location)
.Select(l=>l.Description).Contains("Amsterdam")) &&
(p.PersonRoles.Select(pr=>pr.Role)
.Select(r=>r.Description).Contains("Student")));
query result:
SELECT [t0].[personId] AS [PersonId], [t0].[description] AS [Description]
FROM [Persons] AS [t0]
WHERE (EXISTS(
SELECT NULL AS [EMPTY]
FROM [personlocations] AS [t1]
INNER JOIN [Locations] AS [t2] ON [t2].[locationid] = [t1].[locationid]
WHERE ([t2].[description] = @p0) AND ([t1].[personid] = [t0].[personId])
)) AND (EXISTS(
SELECT NULL AS [EMPTY]
FROM [PersonRoles] AS [t3]
INNER JOIN [Roles] AS [t4] ON [t4].[roleid] = [t3].[roleid]
WHERE ([t4].[description] = @p1) AND ([t3].[personid] = [t0].[personId])
))
using join():
var persons = Persons
.Join(Personlocations, p=>p.PersonId, ps=>ps.Personid,
(p,ps) => new {p,ps})
.Where(a => a.ps.Location.Description =="Amsterdam")
.Join(PersonRoles,
pr=> pr.p.PersonId, r=>r.Personid,(pr,r) => new {pr.p,r})
.Where(a=>a.r.Role.Description=="Student")
.Select(p=> new {p.p});
Query Result:
SELECT [t0].[personId] AS [PersonId], [t0].[description] AS [Description]
FROM [Persons] AS [t0]
INNER JOIN [personlocations] AS [t1] ON [t0].[personId] = [t1].[personid]
INNER JOIN [Locations] AS [t2] ON [t2].[locationid] = [t1].[locationid]
INNER JOIN [PersonRoles] AS [t3] ON [t0].[personId] = [t3].[personid]
INNER JOIN [Roles] AS [t4] ON [t4].[roleid] = [t3].[roleid]
WHERE ([t4].[description] = @p0) AND ([t2].[description] = @p1)
You may want test wich one is faster with large data.
Good luck.
Giuliano Lemes