Question

So I have two tables Site and Contact that have a many to many relationship through the ContactSites table. Both the Site and Contact tables have a Boolean attribute called Deleted. I am trying to attempt to write a LINQ query which lists all the contacts that have a deleted attribute = false and that have related sites which also have a deleted attribute = false

Here is the code I am using:

from c in Contacts
where c.Deleted == false 
select new{c.LName, c.FName, SiteContactSites = 
                            (from cs in ContactSites
                            where cs.Contact_ID == c.ID
                            select new{ cs.Contact_ID,   cs.Site_ID, Sites = 
                                                                (from s in Sites 
                                                                where cs.Site_ID == s.ID &&
                                                                s.Deleted == false 
                                                                select cs).First()}).First()}

but the results seem to be acting like an outer join vs the inner join that I want.

I am specifically looking for a way to do this with nested subqueries and not joins which would be:

from c in Contacts
join cs in ContactSites on c.ID equals cs.Contact_ID
join s in Sites on  cs.Site_ID equals s.ID
where c.Deleted == false && s.Deleted == false
select c

Any help is appreciated

Was it helpful?

Solution

So the following does the trick:

from c in db.Contacts
from co in c.Communities
where co.Deleted == false
select c

Its all in the navigation properties when your using LINQ to Entities so the join is happening at "from co in c.Communities". I think my confusion was I was using LinqPAD which uses LINQ to SQL

this link was helpful and made things clear for me:

http://peter.hahndorf.eu/blog/post/2010/12/31/UsingLinqInManytomanySelectScenarios

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top