Linq Join across three tables
I have three tables and need to write a linq query that pulls from all Activities based on two different joins.
- I need all Activities where the volunteer exist in ActivityVolunteers
- I need all Activities where the OrganizationID is in the Activity table and the volunteer belongs to the organizaiton (OrganizationVolunteers) but not in ActivityVolunteers. The volunteer may not belong to the activity but belongs to the organizaton.
Below is 开发者_如何学Gothe table structure an my attempt at writing the Linq.
Activities- ActivityID
- ActivityName
- OrganizationID
- ActivityID
- VolunteerID
- ActivityRole
- OrganizationID
- VolunteerID
Here is my weak attempt at the linq, I can't figure out joining the two result sets to only get the unique activities.
from a in Activities
join av in ActivityVolunteers on a.ActivityID equals av.ActivityID
where av.VolunteerID==1
select new
{
a.ActivityID,
a.ActivityName,
av.ActivityRole,
a.OrganizationID
}
from org in (from a in Activities
join ov in OrganizationVolunteers on a.OrganizationID equals ov.OrganizationID
where ov.VolunteerID==1
select new
{
a.ActivityID,
a.ActivityName,
ActivityRole = "Prospect",
a.OrganizationID
})
select org
I tried a union but it is duplicating records.
(from a in Activities
join av in ActivityVolunteers on a.ActivityID equals av.ActivityID
where av.VolunteerID==1
select new
{
a.ActivityID,
a.ActivityName,
av.ActivityRole,
a.OrganizationID,
OrganizationName = (from o in Organizations where o.OrganizationID == a.OrganizationID select o.OrganizationName).FirstOrDefault()
}).Union
(from a in Activities
join ov in OrganizationVolunteers on a.OrganizationID equals ov.OrganizationID
where ov.VolunteerID==1
select new
{
a.ActivityID,
a.ActivityName,
ActivityRole = "Prospect",
a.OrganizationID,
OrganizationName = (from o in Organizations where o.OrganizationID == a.OrganizationID select o.OrganizationName).FirstOrDefault()
})
(from a in Activities
join ov in OrganizationVolunteers on a.OrganizationID equals ov.OrganizationID
join av in ActivityVolunteers
on a.ActivityID equals av.VolunteerID into JoinedActVol
from av in JoinedActVol.DefaultIfEmpty()
where ov.VolunteerID==1
select new
{
a.ActivityID,
a.ActivityName,
av.ActivityRole,
a.OrganizationID,
OrganizationName = (from o in Organizations where o.OrganizationID == a.OrganizationID select o.OrganizationName).FirstOrDefault()
}).Union
(from a in Activities
join av in ActivityVolunteers on a.ActivityID equals av.ActivityID
where av.VolunteerID==1 && a.OrganizationID == null
select new
{
a.ActivityID,
a.ActivityName,
av.ActivityRole,
a.OrganizationID,
OrganizationName = ""
})
精彩评论