我有三个表,需要编写一个linq查询,该查询根据两个不同的连接从所有活动中提取。
下面是我尝试编写Linq的表结构。
活动这是我对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()
})
答案 0 :(得分:2)
(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 = ""
})