我是一名EF新手,所以请耐心等待:o
我的数据库中有一个非常直接的关系。 ts_Order表{ID,OrderDate,OrderNumber}和ts_OrderDetails表{ID,ProductId,OrderID}。两个表中的ID都是PK和Identity列。 ts_OrderDetails表中的OrderID是FK,并引用ts_Order表的ID列。
我需要选择所有订单以及每个订单可能包含的每个细节。在SQL中我会写这样的东西:
select * from ts_Order ORD inner join ts_OrderDetails DTL on ORD.ID=DTL.OrderID
哪种效果很好。
当我尝试在EF中做类似的事情时:
List<Order> result = context.Orders.Include("OrderDetails").Where(i => i.ID > 0).ToList();
这是由EF生成的:
SELECT
[Project1].[ID] AS [ID],
[Project1].[OrderDate] AS [OrderDate],
[Project1].[OrderNumber] AS [OrderNumber],
[Project1].[C1] AS [C1],
[Project1].[ID1] AS [ID1],
[Project1].[Product] AS [Product],
[Project1].[OrderID] AS [OrderID]
FROM ( SELECT
[Extent1].[ID] AS [ID],
[Extent1].[OrderDate] AS [OrderDate],
[Extent1].[OrderNumber] AS [OrderNumber],
[Extent2].[ID] AS [ID1],
[Extent2].[Product] AS [Product],
[Extent2].[OrderID] AS [OrderID],
CASE WHEN ([Extent2].[ID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
FROM [dbo].[ts_Order] AS [Extent1]
LEFT OUTER JOIN (SELECT
[ts_OrderDetails].[ID] AS [ID],
[ts_OrderDetails].[Product] AS [Product],
[ts_OrderDetails].[OrderID] AS [OrderID]
FROM [dbo].[ts_OrderDetails] AS [ts_OrderDetails]) AS [Extent2] ON [Extent1].[ID] = [Extent2].[OrderID]
WHERE [Extent1].[ID] > 0
) AS [Project1]
ORDER BY [Project1].[ID] ASC, [Project1].[C1] ASC
为什么生成的查询如此复杂?我错过了什么吗?
-Vinod
答案 0 :(得分:0)
根据我看到的EF生成的一些东西实际上并不是太糟糕。你没有做错任何事。
如果您想获得有关EF用于生成结果的过程的更多信息,这是一个很好的阅读。也是一个很好的指导,使EF尽可能高效。