2010-07-19 87 views
4

我有三個表,需要編寫一個linq查詢,它基於兩個不同的聯接從所有活動中提取。Linq加入三個表

  • 我需要在志願者中ActivityVolunteers
  • 我需要的所有活動,其中OrganizationID是在活動表和志願屬於organizaiton(OrganizationVolunteers),但不存在ActivityVolunteers活動。志願者可能不屬於該活動,但屬於組織。

下面是我在編寫Linq時的表格結構。

活動
  • ActivityID
  • ActivityName
  • OrganizationID
ActivityVolunteers
  • ActivityID
  • VolunteerID
  • ActivityRole
OrganizationVolunteers
  • OrganizationID
  • VolunteerID

這是我在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

我想我正在尋找一個只提供不同的聯盟。 – scottrakes 2010-07-19 20:12:19

+3

'聯合'提供了獨特的答案... – 2010-07-19 20:30:10

+0

這可能是有用的:http://stackoverflow.com/questions/8900077/linq-join-3-tables-with-or-condition/10784347#10784347 – Prasanna 2012-05-28 12:11:47

回答

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 = "" 
    })