我正在使用asp.net C#和VS2012 Express开发MVC Web应用程序。
我有一个表(Organizations
),其中包含与其他两个表(Comments
和Proposals
)的一对多关系。所有三个表都包含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)
如果您使用的是Entity Framework,则可以执行以下任一操作:
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 维护与导航属性的父子关系。
希望这会有所帮助!!
答案 1 :(得分: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);