這是跟進to another user's question。我有5張桌子帶有條件的EF查詢使用連接的查詢
- CompanyDetail
- CompanyContacts
FK to CompanyDetail
- CompanyContactsSecurity
FK to CompanyContact
- UserDetail
- UserGroupMembership
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循環和單獨和更新查詢每家公司我的視角模型。 問:如何鞋拔的permittedContacts變量上,並插入到該查詢:
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;
你說你的目標是得到每個公司的名單,不管聯繫人的數量。但它不可能那麼簡單,或者你只是得到公司名單而不管聯繫人。你能提供一些關於你如何篩選公司的更多細節(用文字)嗎? –
@安妮。公司根本沒有被過濾。我想禁用延遲加載並允許單個SQL查詢給我列出所有公司和相關聯繫人的結果,但限制是不是每個用戶都可以看到每個聯繫人。 – LamonteCristo