简体   繁体   English

Linq Navigation Properties复杂的ID in(从...中选择id)

[英]Linq Navigation Properties complex where ID in (select id from…)

I have two entities Candidate and CandidateLocation where a Candidate can have multiple CandidateLocation entries. 我有两个实体Candidate和CandidateLocation,其中候选人可以有多个CandidateLocation条目。

A CandidateLocation contains the CandidateId, an ISO Country Code (eg US, GB) and a type column (1 = Permitted, 2 = Restricted). CandidateLocation包含CandidateId,ISO国家代码(例如US,GB)和类型列(1 =允许,2 =受限制)。

Rules dictate that if the Candidate does not have any 'Permitted' entries in the CandidateLocation table they can work anywhere. 规则规定如果候选人在CandidateLocation表中没有任何“Permitted”条目,他们可以在任何地方工作。 If they have an explicit 'Permitted' location they can only work in the explicitly permitted locations. 如果他们有明确的“允许”位置,他们只能在明确允许的位置工作。 They can not work in explicilty restricted locations. 他们不能在明确的限制地点工作。

To try an demonstrate this please see the image below (Candidates can have multiple locations I have kept it to one to simplify the illustration) 要试一试这个,请看下面的图片(候选人可以有多个位置,我把它保持为一个,以简化图示)

规则

In SQL one way of achieving this would be the following query 在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)
        )

If anyone knows how to achieve this using linq & Navigation Properties I would greatly appreciate the help. 如果有人知道如何使用linq和导航属性实现这一点,我将非常感谢帮助。

Many thanks 非常感谢

Assuming you've got one-to-many association between Candidates and CandidateLocations 假设你在候选人和候选人之间有一对多的关联

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))
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM