由同一Linq和Lambda表达式生成的两个不同的SQL语句

时间:2010-11-17 12:22:30

标签: c# performance lambda

这是Linq for Left Join -

var Records = from cats in Context.Categories
         join prods in Context.Products on cats.Id equals prods.Category_Id into Cps
         from results in Cps.DefaultIfEmpty()
         select new { CatName = cats.Name, ProdName = results.Name }; 

这是Lambda Expression for same -

var Records = Context.Categories.GroupJoin(Context.Products, c => c.Id, p => p.Category_Id, (c, p) => new { CatName = c.Name, Prods = p });     

Linq使用SQL -

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name], 
[Extent2].[Name] AS [Name1]
FROM  [dbo].[Categories] AS [Extent1]
LEFT OUTER JOIN [dbo].[Products] AS [Extent2] ON [Extent1].[Id] = [Extent2].[Category_Id]

Lambda使用以下SQL -

 SELECT 
 [Project1].[Id] AS [Id], 
 [Project1].[Name] AS [Name], 
 [Project1].[C1] AS [C1], 
 [Project1].[Category_Id] AS [Category_Id], 
 [Project1].[Description] AS [Description], 
 [Project1].[Id1] AS [Id1], 
 [Project1].[Name1] AS [Name1], 
 [Project1].[Price] AS [Price]
 FROM ( SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name], 
[Extent2].[Category_Id] AS [Category_Id], 
[Extent2].[Description] AS [Description], 
[Extent2].[Id] AS [Id1], 
[Extent2].[Name] AS [Name1], 
[Extent2].[Price] AS [Price], 
CASE WHEN ([Extent2].[Category_Id] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
FROM  [dbo].[Categories] AS [Extent1]
LEFT OUTER JOIN [dbo].[Products] AS [Extent2] ON [Extent1].[Id] = [Extent2].[Category_Id])  AS [Project1]
ORDER BY [Project1].[Id] ASC, [Project1].[C1] ASC

我的问题是为什么同一个语句返回不同的SQL?

2 个答案:

答案 0 :(得分:2)

根本不是同一个查询 - 你确实在lambda表达式版本中有GroupJoin - 但是你没有得到与SelectMany相对应的:{/ p>

from results in Cps.DefaultIfEmpty()

由于引入了透明标识符,确切的查询转换变得有点复杂,但我确信这是不同的。

答案 1 :(得分:2)

除了Jon的回复,你还有:

var Records = Context.Categories.GroupJoin(Context.Products, c => c.Id, p => p.Category_Id, (c, p) => new { CatName = c.Name, Prods = p });

其中Prods = p(拉动整个产品记录)Linq查询具有ProdName = results.Name(仅从分组结果中提取名称字符串)。这是相当多的差异。

尝试将Linq输入LinqPad并查看结果窗格中生成的Lamba的内容。