如何使用" SELECT IN"在EF5中

时间:2017-07-04 01:18:30

标签: c# sql entity-framework

我发送了这个罕见的查询,我真的很难将其传递给ef,你能帮我一把吗?

非常感谢您提前

SELECT
    c.*
FROM
    Company c
    JOIN [User] u ON c.id = u.id_company
WHERE
    (
        ( u.id_usertype = 3 )
        AND
        ( u.id = 2135 )
    )

UNION

SELECT
    c.*
FROM
    Company c
    JOIN Company mc ON c.id_company = mc.id
WHERE
    mc.id in
    (
        SELECT
            c.id
        FROM
            Company c
            JOIN [User] u ON c.id = u.id_company 
        WHERE
        (
            ( u.id_usertype = 3 )
            AND
            ( u.id = 2135 )
        )
    )

1 个答案:

答案 0 :(得分:2)

现在您已经解释了子公司/公司关系,我发现查询可以更改为以下查询:

SELECT
    Company.*
FROM
    [User]
    INNER JOIN Company ON [User].id_company = Company.id
WHERE
    [User].id = 2135

UNION

SELECT
    SubCompany .*
FROM
    [User]
    INNER JOIN Company ON [User].id_company = Company.id
    INNER JOIN Company AS SubCompany ON Company.id = SubCompany.id_company
WHERE
    [User].id = 2135

这个基于UNION的查询可以通过更改INNER JOIN Company As SubCompany简化为下面的单个查询,因此它使用OR,因此它与原始公司和子公司相匹配。

SELECT
    SubCompany.*
FROM
    [User]
    INNER JOIN Company ON [User].id_company = Company.id
    LEFT OUTER JOIN Company AS SubCompany ON
    (
        Company.id = SubCompany.id_company
        OR
        Company.id = SubCompany.id
    )
WHERE
    [User].id = 2135

但是,在Linq中,如果您使用的是导航属性,则无法使用复杂的JOIN条件(如果您使用Linq的GroupByJoin操作,则可以使用),因此我们必须通过UNION操作返回Concat

我假设您在实体框架中定义了Company->SubCompany关系,在这种情况下您可以使用SelectMany

var query = dbContext
    .Users
    .Where( u => u.id == 2135 )
    .Select( u => u.Company )
    .Concat(
        dbContext
            .Users
            .Where( u => u.id == 2135 )
            .SelectMany( u => u.Company.SubCompanies )
    );