2011-07-26 76 views
2

我不知道這是形成這個linq查詢的最佳方式,但我剛剛開始,所以任何建議表示讚賞。Linq對實體框架4.1代碼首先產生左外部連接

以下查詢我認爲「報告中有任何項目的項目具有任何屬性,其中大小屬性的waiste大小屬性爲32.」返回報告的位置密鑰,ID和名稱。 (位置是從報表外鍵。)

 var rpts = from x in ctx.Reports 
        where x.ReportItems.Any(y => 
         y.ItemAttributes.Any(z => 
          z.Sizing.WaistSize == 32)) 
        select new { x.Key, x.Location.ID, x.Location.Name }; 

這將產生預期的效果,但SQL看起來不正確我。注意LEFT OUTER JOIN來獲取地點名稱,當它可能只是從第一內得到它加入到同一個表...

SELECT [Extent1].[ReportKey] AS [ReportKey], 
     [Extent2].[LocationID] AS [LocationID], 
     [Extent3].[LocationName] AS [LocationName] 
FROM [Info].[Report] AS [Extent1] 
INNER JOIN [Info].[Location] AS [Extent2] 
ON [Extent1].[LocationKey] = [Extent2].[LocationKey] 
LEFT OUTER JOIN [Info].[Location] AS [Extent3] 
ON [Extent1].[LocationKey] = [Extent3].[LocationKey] 
WHERE EXISTS 
(SELECT 1 AS [C1] 
FROM (SELECT [Extent4].[ReportItemKey] AS [ReportItemKey] 
     FROM [Info].[ReportItems] AS [Extent4] 
     WHERE [Extent1].[ReportKey] = [Extent4].[ReportKey] 
    ) AS [Project1] 
WHERE EXISTS (SELECT 1 AS [C1] 
     FROM [Info].[ItemAttributes] AS [Extent5] 
     INNER JOIN [Info].[Attributes] AS [Extent6] 
        ON [Extent5].[AttributeKey] = [Extent6].[AttributeKey] 
     WHERE ([Project1].[ReportItemKey] = [Extent5].[ReportItemKey]) 
        AND ([Extent6].[WaistSize] = @p__linq__0) 
      ) 
) 

感謝您的時間。

回答

1

如果你想要一個內部聯接,你將不得不寫這樣的事情

from x in ctx.Reports 
join y in ctx.Locations 
on x.LocationKey equals y.ID 
where x.ReportItems.Any(y => 
     y.ItemAttributes.Any(z => 
      z.Sizing.WaistSize == 32)) 
    select new { x.Key, y.ID, y.Name }; 

什麼你寫在select語句說x.Location.ID是導航到該實體的位置,不檢查,看看不管你是否已經處理x.Locationnull的情況,它只是假設你知道如果報告沒有位置,代碼將會中斷。