JasonX JasonX - 1 year ago 91
SQL Question

Writing a nested join with LINQ to Entities

I'm pretty sure there's an example of this somewhere on here, I just can't find it as I don't know the exact terms. So please, be kind.

The problem should be a simple one:

I have an Azure SQL database, somewhat badly designed (ie missing foreign keys and such). As I cannot redesign the database at this point, I have to handle relations manually via querries. As the database is also the bottleneck of our software, I must try and complete queries with as little database hits as possible.

I have entities A, B, C and D. An entity A has several entities B (connected with an unregistered foreign key), an entity B has several entities C and an entity C has several entities D.

I have the ID of entity A, and would like to return a tree of all connected entities up to Ds, as optimally as possible.

Starting off:

from A in dbA.Where(e=>e.Id==IDParameter)
join B in dbB on A.Id equals B.AId into Bs

Now I'd need to do this with every B in Bs for C and again with Cs for D. If I go the obvoius way, and join Ds and Cs first, and then Bs and Cs, and finally the As and Bs, this means joining all Ds with Cs, then all... you get the point, until I finally get to the IDParameter filter. It just seems ineffective.

Is there a proper C# way of doing this in a single query?

Answer Source

You can simulate with manual joins what EF does when you have relationships defined. All you need is to use Group Joins and projections. Something like this:

var result =
    (from a in db.A
     where a.Id == IDParameter
     join b in db.B on a.Id equals b.AId into Bs
     select new
         Bs =
            (from b in Bs
             join c in db.C on b.Id equals c.BId into Cs
             select new
                 Cs =
                    (from c in Cs
                     join d in db.D on c.Id equals d.CId into Ds
                     select new
                         Ds = Ds.ToList()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download