我有三个表,需要编写一个
linq查询,该查询基于两个不同的连接从所有活动中提取.
>我需要在ActivityVolunteers中存在志愿者的所有活动
>我需要所有活动,其中OrganizationID在Activity表中,志愿者属于组织(OrganizationVolunteers),但不属于ActivityVolunteers.志愿者可能不属于该活动但属于组织.
下面是我尝试编写Linq时的表结构.
活动
> ActivityID
> ActivityName
> OrganizationID
ActivityVolunteers
> ActivityID
>志愿者ID
> ActivityRole
OrganizationVolunteers
> OrganizationID
>志愿者ID
这是我对linq的弱尝试,我无法弄清楚加入两个结果集只能获得独特的活动.
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
我尝试了一个联盟,但它重复了记录.
(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 = ""
})