gpt4 book ai didi

c# - linq to sql语法不同但应该得到相同的结果

转载 作者:行者123 更新时间:2023-11-30 19:00:37 25 4
gpt4 key购买 nike

我正在研究表达式树和各种 Linq 语法。我写了以下内容:

using (NorthwindDataContext DB = new NorthwindDataContext())
{
DataLoadOptions dlo = new DataLoadOptions();

// Version 1
dlo.AssociateWith<Customer>(c => c.Orders.Where(o => o.OrderID < 10700).Select(o => o));

// Version 2
dlo.AssociateWith<Customer>(c => from o in c.Orders
where o.OrderID < 10700
select o);
}

版本 1 方法返回错误“子查询不支持运算符‘Select’。”

虽然版本 2 运行良好。据我所知,我正在写完全相同的东西,但一个是使用“点”符号语法,另一个是查询表达式语法。

我是不是漏掉了什么?为什么一个错误而不是另一个“如果”它们实际上是相同的查询?

最佳答案

为了扩展 Daniel 的回答,select o 被称为退化查询表达式 - 它已被 C# 编译器删除。所以你的查询被翻译成:

c.Orders.Where(o => o.OrderID < 10700)

请注意,如果没有 where 子句,编译器仍然包含 Select 调用,因此:

from o in c.Orders
select o

翻译成

c.Orders.Select(o => o)

来自语言规范的第 7.15.2.3 节:

A degenerate query expression is one that trivially selects the elements of the source. A later phase of the translation removes degenerate queries introduced by other translation steps by replacing them with their source. It is important however to ensure that the result of a query expression is never the source object itself, as that would reveal the type and identity of the source to the client of the query. Therefore this step protects degenerate queries written directly in source code by explicitly calling Select on the source. It is then up to the implementers of Select and other query operators to ensure that these methods never return the source object itself.

关于c# - linq to sql语法不同但应该得到相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2059883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com