硬编码值的 LinqPad 问题

LinqPad issues with hard coded values

一直在玩弄 LinqPad(顺便说一句,真的很喜欢它),发现如果我像这样将值硬编码到我的 Select 查询中,它不会喜欢它:

from id in TEST 
select new 
   {
       Id = 0
   }

(在 SQL 选项卡中)显示为:

SELECT NULL 
FROM TEST t0

我认为 LinqPad 会生成类似于

的东西
SELECT 0 AS Id
FROM TEST t0

有没有办法在 LinqPad 中实现该行为?

您给出的 LINQ 查询只是说一个匿名对象,测试中的每条记录的 ID 都设置为 0。将常量发送到 SQL 服务器只是为了让它 return 再次 would/could 只会使查询结果更大。这是 LINQ 的优化之一。如果 LINQ 真的很好,它会生成一个计数,然后 returned 了那么多 0,但是优化器还不是很好,所以它 returns 包含 null 的行。

LinqPad 的结果应该显示一条匿名记录,测试中的每条记录的 ID 属性 设置为 0,就像您要求的那样。更优化的查询是:

Enumerable.Range(0,TEST.Count()).Select(r=>new {Id=0})

在我的测试环境中,包含约 10,000 行的 table 在 0.035 秒内执行,而您的原始版本在 0.070 秒内执行,并且差异随着行数的增加而增加。

Joe Albahari(LinqPad 的作者)在 http://forum.linqpad.net/discussion/312/how-to-make-linqpad-sql-window-return-constants 上回答了这个问题

First, this is a function of the ORM that you're using - in this case, LINQ to SQL, not LINQPad. As it happens, though, LINQ to SQL is doing the right thing here.

LINQ to SQL tries to satisfy your query in the most efficient way possible. So if you ask for a constant, it figures it can supply that constant without round-tripping to a server and back. Unless there's a reason why it needs to include that constant in the query to make it valid, it will leave it out.