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中的一個錯誤?
EF是這樣的豬。制定明確的加入。 – usr
@usr這意味着不使用導航屬性,和(在我的情況下)不使用流利的語法。我試過'加入()'的時候,我總是會看到一些看起來很糟糕的東西。不知道是否可以寫出優雅的'Join()'。 – Stijn
我建議您使用查詢表達式。這讓很多痛苦消失。 – usr