I have a simple db structure as follows
Order
OrderId
OrderItem
OrderItemId | OrderId | BookId | OrderItemTypeId
Book
BookId | AuthorId
I'd like to select a specific Order and all data associated with it's OrderItems plus the Author of the Book sold.
context.Orders.Include(order => order.OrderItems)
.ThenInclude(orderItem => orderItem.Book)
.ThenInclude(book => book.Author)
.Include(order => order.OrderItems)
.ThenInclude(orderItem => orderItem.OrderItemType)
.Where(order => order.Id == 1);
The bit where I get stuck is after this line
.ThenInclude(book => book.Author)
because the lambda will now refer to a Book but I need to be back at the OrderItem level to include the OrderItemType. The only way I seem to be able to do that is to Include the OrderItems again to have that access to include the OrderItemType. It seems incorrect or at the least not very elegant. Can someone point me in the direction of a better approach using method syntax. Thank you
Actually your code is correct. Include
restarts defining includes from the root entity, in your case context.Orders
.
What you can improve here: only non-collection items including, they can be defined by full path:
context.Orders
.Include(order => order.OrderItems)
.ThenInclude(orderItem => orderItem.Book.Author)
.Include(order => order.OrderItems)
.ThenInclude(orderItem => orderItem.OrderItemType)
.Where(order => order.Id == 1);
ThenInclude(orderItem => orderItem.Book.Author)
will include Book and Author.