LINQ 查询中多个 from 选择器的含义是什么
我已经在 LINQ 查询中看到过多次 from 子句,但还没有弄清楚它如何与 TSQL 语句相对应。
var r = from p in products
from d in departments
from c in something
select p;
它有什么作用?
这是否会翻译成 SQL 为 SELECT * FROM 产品、部门等
?
此外,本例中的 select
应该始终是 SelectMany
。我如何知道 select
实际上是 SelectMany
?
I've seen multiple from clauses in a LINQ query a few times now, but have not figured out how that corresponds to a TSQL statement.
var r = from p in products
from d in departments
from c in something
select p;
What does that do?
Does that translate to SQL as SELECT * FROM products, departments, something
?
Also, the select
in this case is supposed to always be a SelectMany
. how do I know when a select
actually is a SelectMany
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从概念上讲,这将转化为如下代码:
基本上,第一个之后的每个
from
都会添加对SelectMany
的额外调用。实际上,在这种情况下,编译器会注意到在最后一个from
子句之后只有一个select
,并且它实际上将转换为:。 ..但我倾向于首先考虑“逻辑”形式。
请注意,在这种情况下,您尚未在
from
子句中使用之前的范围变量,但您可以:That will translate into code conceptually like this:
Basically each
from
after the first one adds an extra call toSelectMany
. Actually, in this case the compiler will notice that after the lastfrom
clause there's just aselect
, and it will actually translate to this:... but I tend to think of the "logical" form first.
Note that in this case you haven't used the earlier range variables within the
from
clauses, but you can:这取决于您使用
from
子句的方式。如果您使用:您的查询将是
CROSS JOIN
,因为所使用的产品和部门之间没有关系。所以类似:显然你应该避免交叉连接。如果您在第二个
from
中使用导航属性:您将使用
INNER
或LEFT JOIN
(EF 将根据您的情况决定使用哪一个)关系中的多重性映射)。所以像这样:It depends on the way how you use your
from
clauses. If you use:Your query will be
CROSS JOIN
because there is no relation between product and department used. So something like:Obviously you should avoid cross joins. If you instead use navigation property in second
from
:you will use either
INNER
orLEFT JOIN
(EF will decide which one to use based on your multiplicity mapping in the relation). So something like:在这种情况下,使用 select 没有任何意义(语义上不正确,您必须使用 SelectMany)
In this case it doesn't make any sense to use select (it's not semantically correct, you must use SelectMany)