我試圖將這個查詢使用linq的查詢語法轉換爲基於方法的語法。如何在不使用查詢語法的情況下在Entity Framework中執行左外連接?
這裏的查詢:
var products = from p in context.Products
join t in context.TopSellings
on p.Id equals t.Id into g
from tps in g.DefaultIfEmpty()
orderby tps.Rating descending
select new
{
Name = p.Name,
Rating = tps.Rating == null ? 0 : tps.Rating
};
上面的查詢生成這個SQL查詢:
{SELECT
[Project1].[Id] AS [Id],
[Project1].[Name] AS [Name],
[Project1].[C1] AS [C1]
FROM (SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
CASE WHEN ([Extent2].[Rating] IS NULL) THEN 0 ELSE [Extent2].[Rating] END AS [C1],
[Extent2].[Rating] AS [Rating]
FROM [dbo].[Products] AS [Extent1]
LEFT OUTER JOIN [dbo].[TopSellings] AS [Extent2] ON [Extent1].[Id] = [Extent2].[Id]
) AS [Project1]
ORDER BY [Project1].[Rating] DESC}
到目前爲止,我已經試過是這樣的:
var products = context.Products
.Join(inner: context.TopSellings.DefaultIfEmpty(),
outerKeySelector: c => c.Id, innerKeySelector: y => y.Id,
resultSelector: (j, k) => new { Name = j.Name, Rating = k.Rating == null ? 0 : k.Rating })
.OrderByDescending(p => p.Rating);
和這個產生了一個不同的sql查詢(關於數據是如何的,這當然有不同的含義) ng在程序中使用):
{SELECT
[Project1].[Id] AS [Id],
[Project1].[Name] AS [Name],
[Project1].[C1] AS [C1]
FROM (SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
CASE WHEN ([Join1].[Rating] IS NULL) THEN 0 ELSE [Join1].[Rating] END AS [C1]
FROM [dbo].[Products] AS [Extent1]
INNER JOIN (SELECT [Extent2].[Id] AS [Id], [Extent2].[Rating] AS [Rating]
FROM (SELECT 1 AS X) AS [SingleRowTable1]
LEFT OUTER JOIN [dbo].[TopSellings] AS [Extent2] ON 1 = 1) AS [Join1] ON [Extent1].[Id] = [Join1].[Id]
) AS [Project1]
ORDER BY [Project1].[C1] DESC}
你的答案會很有幫助,非常感謝!
這種轉換是沒有意義的我,但無論如何,等效方法的語法會用'GroupJoin'其次是'SelectMany',希望你能自己從那裏做。 –
請參閱msdn:https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b – jdweng
@IvanStoev純粹是爲了學習的目的。 –