实体框架子查询
如何在 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
How to write sub queries like these in EF?
select * from table1 where col1 in (select col1 from table2 where col2 = 'xyz')
or
select * from table1 where col1 not in (select col1 from table2 where col2 = 'xyz')
I tried something like these
from t1 in table1
where (from t2 in table2 where col2 = 'xyz' select t2.col1).Contains(t1.col1)
select t1
and
from t1 in table1
where !(from t2 in table2 where col2 = 'xyz' select t2.col1).Contains(t1.col1)
select t1
these queries are working fine LinqPad or Linq to Sql
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这种类型的子查询可以扁平化为联接,这是我选择在此处编写的方式:
SQL 版本:
Linq 版本:
其中
AssociationToTable2
是关系属性 - 它会自动执行联接。或者,如果您没有关系:您可以相应地调整这些
NOT IN
,但我建议您永远不要使用NOT IN
(如果可以避免的话) -性能会下降,这几乎总是意味着设计中的错误。如果您绝对必须以“IN”方式进行,我建议查看这个问题。
This type of subquery can be flattened to a join, which is the way I would choose to write it here:
SQL Version:
Linq Version:
Where
AssociationToTable2
is the relationship property - it does the join automatically. Or, if you don't have a relationship:You can adapt these accordingly for
NOT IN
, although I'd recommend never to useNOT IN
if you can avoid it - performance will sink and it almost always implies an error in design.If you absolutely must do it the "IN" way, I suggest going over the answers in this question.
如果存在外键,您应该只使用关联属性并让 EF 将其转换为正确的联接/子查询,例如:
不确定您的具体场景,但一个关键区别是 EF 默认不执行延迟加载,因此您可能需要 Include() 列(在 linq-to-sql 或使用 linq-to-sql 的 LinqPad 中不需要此)来急切加载它们,或者之后使用 Load() 。
http://msdn.microsoft.com/en-us/library/bb896249。 aspx
如果您最终可以分享一些更具体的模式,我希望我们可以确定这是否是正在发生的事情。
If there's a foreign key in place, you should just use the association properties and let EF translate it into the proper joins/subqueries, like:
Not sure about your specific scenario, but one key difference is that EF defaults to not doing lazy loading, so you may need to Include() columns (wouldn't have needed this in linq-to-sql or LinqPad which uses linq-to-sql) to eager-load them, or alternatively Load() afterwards.
http://msdn.microsoft.com/en-us/library/bb896249.aspx
If you could end up sharing a little bit more concrete schema, we could tell for sure if that's what's going on, I hope.