This is 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 };
This is 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 uses 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]
And Lambda Uses Following 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
My Question is why same statement returning different SQL?
It's not the same query at all - you've got the GroupJoin in the lambda expression version, sure - but you haven't got the SelectMany that would correspond to:
from results in Cps.DefaultIfEmpty()
It gets a bit complicated working out the exact query translation due to the transparent identifiers introduced, but I'm sure that's the difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With