简体   繁体   中英

How to use “SELECT IN” in EF5

I sent this rare query, I really have difficulty being able to pass it to ef, can you please give me a hand with it?

Thank you very much in advance

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

Now that you've explained the Subcompany/Company relationship I see that the query can be changed to the query below:

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

This UNION -based query can be simplified into the single query below by changing the INNER JOIN Company As SubCompany so it uses an OR so it matches both the original company and the sub-companies.

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

However, in Linq you cannot use complex JOIN criteria if you're using Navigation Properties (you can if you use Linq's GroupBy or Join operations), so we must fall-back to a UNION via the Concat operation:

I assume you have a Company->SubCompany relationship defined in Entity Framework, in which case you can use 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 )
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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