开发者

EF - Problem in One To Many Select Query Generated

I am a EF newbie so bear with me :o

I have a very straight forward relationship in my DB. ts_Order table {ID, OrderDate, OrderNumber} and ts_OrderDetails table {ID, ProductId, OrderID}. ID in both the tables are PK and Identity columns. OrderID in ts_OrderDetails table is FK and refers to ID column of ts_Order table.

I need to select all Orders along with every detail that each order may have. In SQL I will write something like this:

select * from ts_Order ORD inner join ts_OrderDetails DTL on ORD.ID=DTL.OrderID

Which works perfectly fine.

When I try to do something similar in EF:

List<Order> result = context.Orders.Include("OrderDetails").Where(i => i.ID > 0).ToList();

This is what is generated by 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

Why is the query generated so complicated? Am I missing something?

-Vinod


Based on some of the stuff I've seen EF generate that actually is not too bad. You haven't done anything wrong.

If you would like to get more information on the process EF uses to generate results this is a good read. Also a good decent guide for making EF as performant as possible.

http://msdn.microsoft.com/en-us/library/cc853327.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜