为什么LINQ-to-EF将某些“包含”呈现为两个单独的JOIN?

时间:2012-03-21 05:37:28

标签: linq entity-framework

  

可能重复:
  EF4.2 extra left outer join to same table

我在父母中有三个实体 - >孩子 - >孙子关系: 订单 - > OrderCustomer - > OrderItem的

每个子实体的父级都有一个不可为空的FK(即OrderItem.OrderCustomerID和OrderCustomer.OrderID)。我想查询一组订单的所有OrderItems(孙子)。在SQL中我会写:

select
    oc.OrderID,
    oi.Quantity,
    oi.SKU
from OrderItems oi
    join OrderCustomers oc on oi.OrderCustomerID = oc.OrderCustomerID
where
    oc.OrderID in (1, 2, 3, 4, 5)

...所以这就是我在LINQ中写的......

OrderItems
    .Where(oi => new[] { 1, 2, 3, 4, 5 }.Contains(oi.OrderCustomer.OrderID))
    .Select(oi => new
    {
        oi.OrderCustomer.OrderID,
        oi.Quantity,
        oi.SKU
    })

...但这是由EF生成的SQL ...

SELECT 
    [Extent1].[OrderCustomerID] AS [OrderCustomerID], 
    [Extent3].[OrderID] AS [OrderID], 
    [Extent1].[Quantity] AS [Quantity], 
    [Extent1].[SKU] AS [SKU]
FROM [dbo].[OrderItems] AS [Extent1]
    INNER JOIN [dbo].[OrderCustomers] AS [Extent2] ON [Extent1].[OrderCustomerID] = [Extent2].[OrderCustomerID]
    LEFT OUTER JOIN [dbo].[OrderCustomers] AS [Extent3] ON [Extent1].[OrderCustomerID] = [Extent3].[OrderCustomerID]
WHERE
    [Extent2].[OrderID] = 1 OR [Extent3].[OrderID] IN (2,3,4,5)

为什么INNER JOIN和OUTER JOIN?

为什么要拆分WHERE子句?

在拥有数百万条记录的数据库中,此查询速度非常慢。

但等等,如果我改变LINQ以在Where ...

之前进行选择
OrderItems
    .Select(oi => new
    {
        oi.OrderCustomer.OrderID,
        oi.Quantity,
        oi.SKU
    })
    .Where(x => new[] { 1, 2, 3, 4, 5 }.Contains(x.OrderID))

...我得到了我想要的SQL ......

SELECT 
    [Extent1].[OrderCustomerID] AS [OrderCustomerID], 
    [Extent2].[OrderID] AS [OrderID], 
    [Extent1].[Quantity] AS [Quantity], 
    [Extent1].[SKU] AS [SKU]
FROM [dbo].[OrderItems] AS [Extent1]
    INNER JOIN [dbo].[OrderCustomers] AS [Extent2] ON [Extent1].[OrderCustomerID] = [Extent2].[OrderCustomerID]
WHERE
    [Extent2].[OrderID] IN (1,2,3,4,5)

所以,我想我可以先通过LINQ Select来帮助EF,但有人知道第一个查询是什么吗?

0 个答案:

没有答案