2

我有一个带有子选择的查询,添加到子选择的每个附加字段都会导致对同一个表的额外连接。我通过删除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 中的错误?

4

1 回答 1

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]
于 2013-08-21T14:00:13.577 回答