子选择导致每个选定字段的连接

时间:2013-08-21 12:33:49

标签: entity-framework-5

我有一个带有子选择的查询,并且添加到subselect的每个附加字段都会导致对同一个表的额外连接。我通过删除Where()子句来减少它在这里的发布,但结果是一样的。

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中的一个错误?

1 个答案:

答案 0 :(得分:1)

好像是/是一个bug。 EF 6的当前夜晚产生了更多更安全的查询。 (目前的测试版,6.0.0-beta1仍有此错误。)

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]