You can try this query:
List<CustomerModel> customers =
(from customer
in context.Customers
select new {
customer.Id,
customer.Name,
Orders = customer.Orders
.OrderByDescending(o => o.OrderDate)
.Select(o => new {
Order = o,
Items = o.Items
.Select(i => new {
Item = i,
Article = i.Article
})
})
})
.AsEnumerable()
.Select(x => new CustomerModel
{
Id = x.Id,
Name = x.Name,
Orders = x.Orders.Select(o => o.Order).ToArray()
})
.ToList();
Although Item
and Article
in the inner anonymous object are not used they will be loaded and Entity Framework's relationship fixup should set the correct navigation properties for Order.Items
and Item.Article
- as long as the relationships are not many-to-many and you don't use AsNoTracking
.
If you want to perform this as a no-tracking query, you basically have to set the navigation properties yourself. It should be possible by moving the following additional Select
between AsEnumerable()
and Select(...)
:
// .AsEnumerable()
.Select(x => new {
Id = x.Id,
Name = x.Name,
Orders = x.Orders.Select(y => {
y.Order.Items = y.Items.Select(z => {
z.Item.Article = z.Article;
return z.Item;
}).ToArray();
return y;
})
})
// .Select(x => new CustomerModel ...