У меня есть запрос, который ищет все места в заказе, отсортированные по дням. Когда я проверяю сервер, какой запрос выполняется, я вижу множественное соединение к одной и той же таблице на одних и тех же ключах
var parcourt = this.DataService.From<OrderItem>()
.Where(i => i.OrderId == orderId && i.Product.ProductTypeId == (int)ProductTypes.Accommodation)
.OrderBy(i => i.DayNumber)
.ThenBy(i => i.OrderItemId)
.Select(i => new
{
i.OrderItemId,
i.DayNumber,
i.Product.Establishment.Address,
i.Product.Establishment.Coordinates
});
Если вы проверите полученный SQL (как показано ToTraceString
), вы увидите два объединения в таблице Products
и Establishments
.
SELECT
[Project1].[OrderItemId] AS [OrderItemId],
[Project1].[DayNumber] AS [DayNumber],
[Project1].[Address] AS [Address],
[Project1].[EstablishmentId] AS [EstablishmentId],
[Project1].[Latitude] AS [Latitude],
[Project1].[Longitude] AS [Longitude]
FROM ( SELECT
[Extent1].[OrderItemId] AS [OrderItemId],
[Extent1].[DayNumber] AS [DayNumber],
[Extent4].[Address] AS [Address],
[Extent5].[EstablishmentId] AS [EstablishmentId],
[Extent5].[Latitude] AS [Latitude],
[Extent5].[Longitude] AS [Longitude]
FROM [dbo].[OrderItems] AS [Extent1]
INNER JOIN [dbo].[Products] AS [Extent2] ON [Extent1].[ProductId] = [Extent2].[ProductId]
LEFT OUTER JOIN [dbo].[Products] AS [Extent3] ON [Extent1].[ProductId] = [Extent3].[ProductId]
LEFT OUTER JOIN [dbo].[Establishments] AS [Extent4] ON [Extent3].[EstablishmentId] = [Extent4].[EstablishmentId]
LEFT OUTER JOIN [dbo].[Establishments] AS [Extent5] ON [Extent3].[EstablishmentId] = [Extent5].[EstablishmentId]
WHERE (1 = [Extent2].[ProductTypeId]) AND ([Extent1].[OrderId] = @p__linq__0)
) AS [Project1]
ORDER BY [Project1].[DayNumber] ASC, [Project1].[OrderItemId] ASC
Как я могу предотвратить двойное соединение этой linq-сущности на столе? Как я могу переписать запрос, чтобы избежать этой ситуации?
Структура таблицы выглядит следующим образом (упрощенно):
Это запрос