C#, linq to sql, 为嘛single生成的sql 是top (2)而不是top (1)

2012-04-20 19:46:38 +08:00
 avatasia
SELECT TOP (2)
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Extent1].[Url] AS [Url],
[Extent1].[ParentId] AS [ParentId]
FROM [dbo].[MenuItem] AS [Extent1]
WHERE [Extent1].[ParentId] IS NULL
4892 次点击
所在节点    问与答
10 条回复
avatasia
2012-04-20 19:48:32 +08:00
好吧,single 如果结果多于2个就抛出异常
thereisnoif
2012-04-24 18:57:15 +08:00
生成的sql应该是:
SELECT [t0].[id] as [id]
FROM [dbo].[table] as [t0]
WHERE [t0].[id] IS NULl
这样的,没有TOP语句;

Single扩展方法Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists.

http://msdn.microsoft.com/en-us/library/bb535118.aspx
avatasia
2012-04-24 19:35:16 +08:00
@thereisnoif 你错了
thereisnoif
2012-04-24 23:34:15 +08:00
@avatasia 我用linqpad实验的结果显示,Single生成的sql是没有Top的;First会产生Top语句;不过http://stackoverflow.com/questions/8829314/why-does-single-linq-extension-method-create-a-query-select-top2 确实是如你所说的情况。
也许是Linqpad显示的sql有问题?
明天去看看Single源码去
Ricepig
2012-04-25 00:12:23 +08:00
是要检查是不是多于1个吧。这个时候返回top 2不是很合理?
avatasia
2012-04-25 09:28:22 +08:00
@thereisnoif 你要用sql server profiler去看
avatasia
2012-04-25 09:29:09 +08:00
@Ricepig single 是取唯一的一个,first是取多个中的第一个,所以single要做多于1的判断
thereisnoif
2012-04-25 10:49:56 +08:00
@avatasia 很奇怪啊,我确实用sql profiler看了,是没有top的。。。
难道跟Linq版本有关,我是4.0;
C#查询是:
var ret = App_Case_Alls.Single(c => c.Case_type == 1);
Console.Write(ret);

sql profilerie截到的sql是:

exec sp_executesql N'SELECT [t0].[case_id] AS [Case_id], [t0].[case_type] AS [Case_type], [t0].[req_no] AS [Req_no]
FROM [app_Case_All] AS [t0]
WHERE [t0].[case_type] = @p0',N'@p0 int',@p0=1
Ricepig
2012-04-25 15:21:34 +08:00
@avatasia 我说的就是这个意思。。。。
thereisnoif
2012-04-25 16:18:09 +08:00
@avatasia 终于弄清楚了,用Entity Framework的Linq查询Single,确实生成的sql是TOP(2); 但用Linq-to-Sql的话,Single是不会有产生TOP语句的;我的实验都是直接用Linq-to-sql的,所以才产生困扰。see http://stackoverflow.com/questions/10309100/does-linq2sql-generated-sql-contains-top-or-not-when-single-is-used

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/32759

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX