这是一个跟进to another user's question。我有5张桌子
FK to CompanyDetail
FK to CompanyContact
FK to UserDetail
如何退回所有公司并在同一查询中包含联系人?我想包括零联系的公司。
公司与联系人之间有1对多的关联,但不是每个用户都可以查看每个联系人。我的目标是获取每个公司的列表,无论联系人的数量如何,但包括联系人数据。
现在我有这个有效的查询:
var userGroupsQueryable = _entities.UserGroupMembership
.Where(ug => ug.UserID == UserID)
.Select(a => a.GroupMembership);
var contactsGroupsQueryable = _entities.CompanyContactsSecurity;//.Where(c => c.CompanyID == companyID);
/// OLD Query that shows permitted contacts
/// ... I want to "use this query inside "listOfCompany"
///
//var permittedContacts= from c in userGroupsQueryable
//join p in contactsGroupsQueryable on c equals p.GroupID
//select p;
然而,当我需要获得所有公司的所有联系人时,这是低效的,因为我使用For..Each循环并单独查询每个公司并更新我的viewmodel。 问题:我如何窃取上面的allowedContacts变量并将其插入此查询中:
var listOfCompany = from company in _entities.CompanyDetail.Include("CompanyContacts").Include("CompanyContactsSecurity")
where company.CompanyContacts.Any(
// Insert Query here....
// b => b.CompanyContactsSecurity.Join(/*inner*/,/*OuterKey*/,/*innerKey*/,/*ResultSelector*/)
)
select company;
我尝试这样做导致:
var listOfCompany = from company in _entities.CompanyDetail.Include("CompanyContacts").Include("CompanyContactsSecurity")
where company.CompanyContacts.Any(
// This is concept only... doesn't work...
from grps in userGroupsQueryable
join p in company.CompanyContactsSecurity on grps equals p.GroupID
select p
)
select company;
答案 0 :(得分:1)
也许就是这样。
var q = from company in _entities.CompanyDetail
where
(from c in userGroupsQueryable
join p in contactsGroupsQueryable on c equals p.GroupID
where company.CompanyContacts.Any(cc => cc.pkCompanyContact == p.fkCompanyContact)
select p
).Any()
select new
{
Company = company,
Contacts = company.CompanyContacts
};
答案 1 :(得分:0)
以下代码查询所有公司,并仅附加允许用户查看的联系人。我不知道这是多么有效,或者是否有办法让它更快,但它有效。
var userGroupsQueryable = _entities.UserGroupMembership.Where(ug => ug.UserID == UserID)
.Select(a => a.GroupMembership);
var contactsGroupsQueryable = _entities.CompanyContactsSecurity;
var listOfCompanies =
from company in _entities.CompanyDetail
select new
{
Company = company,
Contacts = (from c in userGroupsQueryable
join p in contactsGroupsQueryable on c equals p.GroupID
where company.CompanyContacts.Any(cc => cc.CompanyID == p.CompanyID)
select p.CompanyContacts)
};