Note that there are some explanatory texts on larger screens.

plurals
  1. POEF5 code first ordering nested items
    primarykey
    data
    text
    <p>I'm stumbling upon a small issue when retrieving a set of data with Entity Framework 5 Code First. Here's my code:</p> <pre><code>var data = context.Customers .Include("Orders") .Include("Orders.Items") .Include("Orders.Items.Article").ToArray(); foreach (var customer in data) { customer.Orders = customer.Orders.OrderByDescending(o =&gt; o.OrderDate).ToArray(); } </code></pre> <p>This works (whoo!). But, I'm trying to get that <code>foreach</code> out of there, I want the database engine to remain responsible for processing data. How do I do this? </p> <p>I've tried this type of join:</p> <pre><code>var data = from customer in context.Customers select new { customer.Id, customer.Name, // customer.Orders below doesn't have an Include() to include order items Orders = customer.Orders.OrderByDescending(b =&gt; b.OrderDate) }; // Translate anonymous object to actual models var customers = new List&lt;CustomerModel&gt;(); foreach (var customer in data) { customers.Add(new CustomerModel() { Id = customer.Id, Name = customer.Name, Orders = customer.Orders.ToArray() }); } </code></pre> <p>But, as the comment says, <code>customer.Orders</code> doesn't have an <code>Include()</code> method to include items and articles belonging to those items. I then tried to get in from the <code>context</code> instead of the <code>customer</code> object:</p> <p><code>Orders = context.Orders.Include("Items").Where(o =&gt; o.Id == customer.Id)</code></p> <p>But this results in a runtime exception that <code>Include()</code> cannot be used this way (in nested queries?):</p> <pre><code>Method 'System.Data.Entity.Infrastructure.DbQuery`1[MyTests.Models.OrderModel] Include(System.String)' declared on type 'System.Data.Entity.Infrastructure.DbQuery`1[MyTests.Models.OrderModel]' cannot be called with instance of type 'System.Data.Objects.ObjectQuery`1[MyTests.Models.OrdersModel]' </code></pre> <p>Is something like that even possible, nesting it out like that?</p> <p><strong>How do I make the database process the data instead of using a <code>foreach</code> in my first code block?</strong></p> <p>Thanks in advance.</p> <p>JP</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload