【发布时间】:2010-01-02 16:08:22
【问题描述】:
如何在 EF 中编写这样的子查询?
select * from table1 where col1 in (select col1 from table2 where col2 = 'xyz')
或
select * from table1 where col1 not in (select col1 from table2 where col2 = 'xyz')
我尝试过类似的方法
from t1 in table1
where (from t2 in table2 where col2 = 'xyz' select t2.col1).Contains(t1.col1)
select t1
和
from t1 in table1
where !(from t2 in table2 where col2 = 'xyz' select t2.col1).Contains(t1.col1)
select t1
这些查询运行良好 LinqPad 或 Linq to Sql
【问题讨论】:
-
如果现有答案不是您想要的,请在您尝试使用您发布的那些查询表达式时发布发生了什么。你得到一个编译时错误吗?运行时错误?错误是什么?还是您根本没有得到预期的结果?
-
首先感谢您的即时回复!这就是我想要完成的 - select * from table1 where somestringmanipulation(col1) in (select somestringmanipulation(col1) from table2 where col2 = 'xyz') where table1 和 table2 没有任何关系。尝试使用 Contains 时出现以下错误,但它在 LinqPad 中给出结果 LINQ to Entities 无法识别方法 'Boolean Contains[Int32](System.Linq.IQueryable`1[System.Int32], Int32 )' 方法,并且该方法不能翻译成 store 表达式。
-
如果不使用 IN 或 NOT IN,我认为我无法做到这一点,暂时我计划使用存储过程,稍后我会研究 stackoverflow.com/questions/374267/…
-
您所写的查询绝对不需要
IN/NOT IN。我不怀疑实际情况比您的示例更复杂-但我建议您尝试找到一种使用简单联接的方法,因为它们更易于阅读/维护并且通常会带来更好的性能(尤其是@ 987654328@,这是一个可怕的)。或许如果你提供一个更具体的例子,有人可以帮助你。 -
请用您正在尝试做的事情更新原始问题;我会相应地编辑我的答案。并且具体一点——一些 .NET 字符串操作可以转换为 SQL,而有些则不能。
标签: .net entity-framework subquery