我有一个基于两个表的查询,它们之间有一个导航属性:
// idOrder shared between classes as nav property
public partial class OrderItem
{
public int idOrder { get; set; }
public int idInventory { get; set; }
public virtual Order Order { get; set; }
}
public partial class Order
{
public Nullable<short> idSite { get; set; }
public int idOrder { get; set; }
public Nullable<System.DateTime> genDate { get; set; }
public virtual ICollection<OrderItem> OrderItems { get; set; }
}
当我对它们运行查询时,它似乎与预期的内部联接一起正常工作:
var orderItems = dbc.orderItems
.Where(oi => oi.Order.genDate > lastWeek)
.Select(oi => oi.idInventory);
返回内部联接查询
SELECT
[Extent1].[idInventory] AS [idInventory]
FROM [dbo].[Order_ITEMS] AS [Extent1]
INNER JOIN [dbo].[Order] AS [Extent2] ON [Extent1].[idOrder] = [Extent2].[idOrder]
WHERE [Extent2].[genDate] > @p__linq__0
但是,如果我改为运行非常相似的查询
var orderItems = dbc.orderItems
.Where(oi => oi.Order.idSite == 1234)
.Select(oi => oi.idInventory);
相反,我得到了这个极其昂贵的外连接查询:
SELECT
[Extent1].[idInventory] AS [idInventory]
FROM [dbo].[Order_ITEMS] AS [Extent1]
LEFT OUTER JOIN [dbo].[Order] AS [Extent2] ON [Extent1].[idOrder] = [Extent2].[idOrder]
WHERE CAST( [Extent2].[idSite] AS int) = @p__linq__0
我相信这是因为idSite是可以为空的,但在这种情况下我并不是要求返回空站点,所以外连接在这里似乎没用。为什么此更改会导致查询更改其连接类型,以及如何阻止它?