2013-08-21 49 views
2

我有一個查詢與一個子選擇,並且每個附加字段添加到子選擇會導致額外連接到同一個表。我通過刪除Where()子句來減少它的發佈,但結果是一樣的。Subselect導致每個選定字段的連接

DbContext.Customer 
    .Select(item => new 
    { 
     ID = item.Id, 
     Name = item.NameCompany, 
     BaseAddress = item.Customer_Address 
      .Select(child => new 
      { 
       Street = child.Address.Street, 
       Number = child.Address.Number, 
       PostalCode = child.Address.PostalCode, 
       City = child.Address.City 
      }) 
      .FirstOrDefault() 
    }) 
    .Select(item => new 
    { 
     item.ID, 
     item.Name, 
     item.BaseAddress.Street, 
     item.BaseAddress.Number, 
     item.BaseAddress.PostalCode, 
     item.BaseAddress.City 
    }) 
    .First(); 
SELECT TOP (1) 
[Extent1].[Id] AS [Id], 
[Extent1].[NameCompany] AS [NameCompany], 
[Element1].[Street] AS [Street], 
[Element1].[Number] AS [Number], 
[Element1].[PostalCode] AS [PostalCode], 
[Element1].[City] AS [City] 
FROM [dbo].[Customer] AS [Extent1] 
OUTER APPLY (SELECT TOP (1) 
    [Limit1].[AddressId] AS [AddressId], 
    [Extent3].[Id] AS [Id], 
    [Extent3].[Street] AS [Street], 
    [Extent4].[Id] AS [Id1], 
    [Extent4].[Number] AS [Number], 
    [Extent5].[Id] AS [Id2], 
    [Extent5].[PostalCode] AS [PostalCode], 
    [Extent6].[Id] AS [Id3], 
    [Extent6].[City] AS [City] 
    FROM  (SELECT TOP (1) 
     [Extent2].[AddressId] AS [AddressId] 
     FROM [dbo].[Customer_Address] AS [Extent2] 
     WHERE [Extent1].[Id] = [Extent2].[CustomerId]) AS [Limit1] 
    LEFT OUTER JOIN [dbo].[Address] AS [Extent3] ON [Limit1].[AddressId] = [Extent3].[Id] 
    LEFT OUTER JOIN [dbo].[Address] AS [Extent4] ON [Limit1].[AddressId] = [Extent4].[Id] 
    LEFT OUTER JOIN [dbo].[Address] AS [Extent5] ON [Limit1].[AddressId] = [Extent5].[Id] 
    LEFT OUTER JOIN [dbo].[Address] AS [Extent6] ON [Limit1].[AddressId] = [Extent6].[Id]) AS [Element1] 

我可以改變我的查詢,使之加入一次?或者這可能是EF中的一個錯誤?

+0

EF是這樣的豬。制定明確的加入。 – usr

+0

@usr這意味着不使用導航屬性,和(在我的情況下)不使用流利的語法。我試過'加入()'的時候,我總是會看到一些看起來很糟糕的東西。不知道是否可以寫出優雅的'Join()'。 – Stijn

+0

我建議您使用查詢表達式。這讓很多痛苦消失。 – usr

回答

1

似乎它是/是一個錯誤。目前EF 6每晚都會產生更多更精確的查詢。 (目前的beta版,6.0.0-beta1仍然有這個bug)。

SELECT TOP (1) 
    [Extent1].[Id] AS [Id], 
    [Extent1].[NameCompany] AS [NameCompany], 
    [Limit1].[Street] AS [Street], 
    [Limit1].[Number] AS [Number], 
    [Limit1].[PostalCode] AS [PostalCode], 
    [Limit1].[City] AS [City] 
    FROM [dbo].[Customer] AS [Extent1] 
    OUTER APPLY (SELECT TOP (1) 
     [Extent3].[Street] AS [Street], 
     [Extent3].[City] AS [City], 
     [Extent3].[PostalCode] AS [PostalCode], 
     [Extent3].[Number] AS [Number] 
     FROM [dbo].[Customer_Address] AS [Extent2] 
     INNER JOIN [dbo].[Address] AS [Extent3] ON [Extent2].[AddressId] = [Extent3].[Id] 
     WHERE [Extent1].[Id] = [Extent2].[CustomerId]) AS [Limit1] 
+0

使用EF你永遠無法確定哪些perf缺陷是bug,哪些是缺陷設計。 – usr