如何於LINQ中使用TSQL的Left Outer Join
延續上一篇的測試資料,假設要以t1為主對t2做Left Outer Join,那麼LINQ的程式碼如下:
1: var query = from p in context.t1
2: join q in context.t2
3: on p.c1 equals q.c1 into r
4: from s in r.DefaultIfEmpty()
5: select new { p.c1, p.c2, c3 = s.c1.GetValueOrDefault(-1),c4 = s.c2 };
6: foreach (var item in query)
7: {
8: Response.Write(string.Format("{0},{1},{2},{3}<br/>", item.c1, item.c2, item.c3
9: , string.IsNullOrEmpty(item.c4) ? "-" : item.c4));
10: }
其中需特別注意在第3列將p和q join的結果以into子句暫存於r,必須再利用第4列的from子句來產生補充查詢,才能於第5列選取t2的欄位。
執行結果如下:
同樣的可以使用DataContext.GetCommand方法取得實際執行的TSQL敘述(如下)。
1: SELECT [t0].[c1], [t0].[c2], COALESCE([t1].[c1],@p0) AS [c3], [t1].[c2] AS [c4]
2: FROM [dbo].[t1] AS [t0]
3: LEFT OUTER JOIN [dbo].[t2] AS [t1] ON [t0].[c1] = [t1].[c1
參考資料: