实体框架子查询

Gok*_*ath 3 .net entity-framework subquery

如何在EF中编写这样的子查询?

select * from table1 where col1 in (select col1 from table2 where col2 = 'xyz')
Run Code Online (Sandbox Code Playgroud)

要么

select * from table1 where col1 not in (select col1 from table2 where col2 = 'xyz')
Run Code Online (Sandbox Code Playgroud)

我试过这样的东西

from t1 in table1
where (from t2 in table2 where col2 = 'xyz' select t2.col1).Contains(t1.col1)
select t1
Run Code Online (Sandbox Code Playgroud)

from t1 in table1
where !(from t2 in table2 where col2 = 'xyz' select t2.col1).Contains(t1.col1)
select t1
Run Code Online (Sandbox Code Playgroud)

这些查询工作正常LinqPad或Linq到Sql

Aar*_*ght 6

这种类型的子查询可以展平为连接,这是我选择在此处编写它的方式:

SQL版本:

SELECT t1.col1, t1.col2, t1.col3, ...
FROM table1 t1
INNER JOIN table2 t2
    ON t1.col1 = t2.col1
WHERE t2.col2 = 'xyz'
Run Code Online (Sandbox Code Playgroud)

Linq版本:

var query =
    from t1 in context.Table1
    where t1.AssociationToTable2.Col2 == "xyz"
    select new { t1.Col1, t1.Col2, ... };
Run Code Online (Sandbox Code Playgroud)

AssociationToTable2关系属性在哪里- 它自动进行连接.或者,如果你没有关系:

var query =
    from t1 in context.Table1
    join t2 in context.Table2
        on t1.Col1 equals t2.Col1
    where t2.Col2 == "xyz"
    select new { t1.Col1, t1.Col2, ... };
Run Code Online (Sandbox Code Playgroud)

你可以相应地调整它们NOT IN,虽然我建议永远不要使用,NOT IN如果你可以避免它 - 性能会下降,它几乎总是暗示设计错误.

如果你绝对必须采用"IN"方式,我建议在这个问题中回答这些问题.