1

我正在使用 asp.net C# 和 VS2012 Express 开发一个 MVC Web 应用程序。

我有一个表 ( ) 与其他两个表 (和)Organizations具有一对多关系。所有三个表都包含一个字段来维护关系。所有三个表都有一个字符串字段。CommentsProposalsOrganizationIDAddedBy

我想找到所有组织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();

谢谢你的帮助。

4

2 回答 2

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维护与导航属性的父子关系。

希望这会有所帮助!

于 2013-08-21T18:50:01.863 回答
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);
于 2013-08-21T18:47:58.247 回答