我有两个实体Candidate和CandidateLocation,其中候选人可以拥有多个CandidateLocation条目。
CandidateLocation包含CandidateId,ISO国家代码(例如US,GB)和类型列(1 =允许,2 =受限制)。
规则规定如果候选人在CandidateLocation表中没有任何“Permitted”条目,他们可以在任何地方工作。如果他们有明确的“允许”位置,他们只能在明确允许的位置工作。他们不能在明确的限制地点工作。
要尝试演示,请参阅下面的图片(考生可以有多个位置我将其保留为一个以简化插图)
在SQL中,实现此目的的一种方法是以下查询
SELECT *
FROM Candidate
WHERE Candidate.IsArchived = 0
AND
-- Do not inlude restricted locations (RestrictionStatus = 2)
Candidate.CandidateId NOT IN (SELECT CandidateId FROM CandidateLocation WHERE IsArchived = 0 AND CountryISOCode = @Location AND RestrictionStatus = 2)
AND
(
-- Include Explicit Permitted Locations
Candidate.CandidateId IN (SELECT CandidateId FROM CandidateLocation WHERE IsArchived = 0 AND CountryISOCode = @Location AND RestrictionStatus = 1)
OR
-- Include Candidates with no Explicit Permitted Locations
Candidate.CandidateId NOT IN (SELECT CandidateId FROM CandidateLocation WHERE IsArchived = 0 AND RestrictionStatus = 1)
)
如果有人知道如何使用linq&导航属性我非常感谢帮助。
非常感谢
答案 0 :(得分:6)
假设你在候选人和候选人地点之间有一对多的关联
Context.Candidates.Where(c => c.IsArchived == 0 &&
!c.CandidateLocations.Any(
l => l.CountryISOCode == location && l.RestrictionStatus == 2) &&
(c.CandidateLocations.Any(
l => l.CountryISOCode == location && l.RestrictionStatus == 1) ||
!c.CandidateLocations.Any(
l => l.RestrictionStatus == 1))
);