2013-08-21 52 views
1

我正在開發一個使用asp.net C#和VS2012 Express的MVC Web應用程序。Linq一對多聯盟

我有一個表(Organizations)與其他兩個表(CommentsProposals)之間的一對多關係。所有三個表格都包含一個OrganizationID字段以維護關係。所有三個表都有一個AddedBy字符串字段。

我想查找所有組織,其中的Organization.AddedBy="Joe"Comments.AddedBy="Joe"Proposals.AddedBy="Joe"

這些查詢會進行連接,但我正在查找僅包含Organizations' fields的聯合。

// Find organizations created by this person. 
IQueryable<Organization> org = from m in context.Organizations 
where m.AddedBy.Equals("Joe") 
select m; 

// Find Comments created by this person. 
IQueryable<Comment> comment = from m in context.Comments 
where m.AddedBy.Equals("Joe") 
select m; 

// Join our two queries. 
IQueryable<Comment> organizations = (from item in org 
join c in comment on item.OrganizationID equals c.OrganizationID 
select item).Distinct(); 

// Find Proposals created by this person. 
IQueryable<Proposal> proposal = from m in context.Proposals 
where m.AddedBy.Equals("Joe") 
select m; 

// Join our two queries. 
organizations = (from item in organizations 
join c in proposal on item.OrganizationID equals c.OrganizationID 
select item).Distinct(); 

感謝您的幫助。

+0

問題是什麼?哪部分不工作? –

回答

2

如果您正在使用實體框架,你可以做兩種:

var orgs = context.Organizations 
        .Where(O => O.AddedBy.Equals("Joe") || 
           O.Comments.Any(C => C.AddedBy.Equals("joe")) || 
           O.Proposals.Any(P => P.AddedBy.Equals("joe"))); 

由於EF保持與親子關係導航屬性。

希望這會有所幫助!

+0

輝煌。簡潔。 Merci Kundan! –

0

因此,您正在尋找三種不同的組合,全部組合在一起。在只查詢每個這樣的三件事情,然後使用Union將它們組合起來:

string user = "Joe"; 

var addedOrganizations = context.Organizations.Where(org => org.AddedBy == user); 

var orgsWithUsersComments = from org in context.Organizations 
    join c in context.Comments 
    on org.OrganizationID equals c.OrganizationID 
    where c.AddedBy == user 
    select org; 

var orgsWithUsersProposals = from org in context.Organizations 
    join p in context.Proposals 
    where p.AddedBy == user 
    select org; 

var combinedResults = addedOrganizations.Union(orgsWithUsersComments) 
    .Union(orgsWithUsersProposals);