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
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.