Search code examples
c#linqsql-to-linq-conversionlinq-method-syntax

LINQ Method Syntax to INCLUDE 4 Levels Deep


I have been searching without success (or not knowing how to search for this properly) so I come to you.

Check out these test classes:

public class A {
    int Id;
    ICollection<B> Bs;
}
public class B {
    int Id;
    int AId;
    ICollection<C> Cs;
}
public class C {
    int Id;
    int BId;
    ICollection<D> D;
}
public class D {
    int Id;
    int CId;
    bool Show;
}

What I'm trying to do is use eager loading to get all these classes in 1 call (making sure the DB only gets called once).

Below is the actual TSQL I want to convert to LINQ Method syntax (I think that the correct lingo) and not LINQ Query syntax.

SELECT *
FROM A
LEFT JOIN B ON B.AId = A.Id
LEFT JOIN C ON C.BId = B.Id
LEFT JOIN D ON D.CId = C.Id
WHERE A.Id = 1

Here's what I've gotten so far

var x = db.A
        .Include(a => a.B)
        .Include(a => a.Bs.Select(b => b.C)
        // How do I get D?
        .FirstOrDefault(a => a.Id == 1);

While I don't think it's important, I'd like to point out, just in case, that in the end, I need to do some things to A, and at a later point, I will need to get all the D's that have Show == true.


Solution

  • Your sample model is a little inconsistent, you use different names for your model classes and your LINQ query e.g. B vs Bs. That aside, I believe you can achieve what you want by nesting another Select() in your inner query.

    e.g.

    var x = db.A
        .Include(a => a.Bs.Select(b => b.Cs.Select(c => c.Ds))
        .FirstOrDefault(a => a.Id == 1);