Search code examples
c#linqentity-frameworklinq-to-entities

query and create objects with a one to many relationship using LINQ


In the DB, I have a two tables with a one-to-many relationship:

orders          suborders
-----------     -----------
id              id
name            order_id
                name

I'd like to query these tables and end up with a list of order objects, each of which contains a list (or empty list) of suborder objects. I'd also like to do this in a single DB query so it performs well.

In traditional SQL query land, I'd do something like (forgive the pseudocode):

rs = "select o.id, o.name, so.id, so.name from orders o left join suborders so on o.id = so.order_id order by o.id"

orders = new List<Order>
order = null
foreach (row in rs) {
    if (order == null || row.get(o.id) != order.id) {
        order = new Order(row.get(o.id), row.get(o.name), new List<Suborders>)   
        orders.add(order)
    }    

    if (row.get(so.id) != null) {
        order.suborders.add(new Suborder(row.get(so.id) row.get(so.name))
    }
}

Is there a way to get this same resulting object structure using LINQ-to-Entities? Note that I want to get new objects out of the query, not the Entity Framework generated objects.

The following gets me close, but throws an exception: "LINQ to Entities does not recognize the method..."

var orders = 
    (from o in Context.orders
     join so in Context.suborders on o.id equals so.order_id into gj
     select new Order 
     {
         id = o.id,
         name = o.name,
         suborders = (from so in gj select new Suborder
         {
             so.id,
             so.name
         }).ToList()
     }).ToList();

Solution

  • The solution ends up being pretty simple. The key is to use a group join to get SQL to do the left join to suborders, and add a second ToList() call to force the query to be run so you're not trying to do object creation on the SQL server.

    orders = Context.orders
        .GroupJoin(
            Context.suborders,
            o => o.id,
            so => so.order_id,
            (o, so) => new { order = o, suborders = so })
        .ToList()
        .Select(r => new Order
        {
            id = r.order.id,
            name = r.order.name,
            suborders = r.suborders.Select(so => new Suborder
            {
                id = so.id,
                name = so.name
            }.ToList()
        }).ToList();
    

    This code only makes a single query to SQL for all objects and their child objects. It also lets you transform the EF objects into whatever you need.