SelectMany creates lots of SQL select statements instead of one with join

后端 未结 1 524
遇见更好的自我
遇见更好的自我 2021-01-05 00:47

I\'m writing a query with SelectMany and checked SQL it generates in LINQPad. The query is very simple.

Let\'s say I have 3 entities: Customer

1条回答
  •  天涯浪人
    2021-01-05 01:13

    You should use the following for your query (to query for the order items of a specific customer with someId):

    context.Customers.Where(c => c.Id == someId)
        .SelectMany(c => c.Orders.SelectMany(o => o.OrderItems))
    

    Or - to reproduce the behaviour of First() but with a single DB query:

    context.Customers.Take(1)
        .SelectMany(c => c.Orders.SelectMany(o => o.OrderItems))
    

    You original query loads the customer with First (query 1), then lazy loading loads the Orders collection of that customer (query 2), then lazy loading again loads the order items collection for each loaded Order (query 3 to n). To avoid all those multiple queries you must not use a "query execution method" like First() or ToList(), etc. inside of your query expression.

    0 讨论(0)
提交回复
热议问题