retrieving data from multiple nested table levels RRS feed

  • Question

  • User65893105 posted

    I have a master table with a detail table linked by a foreign key (integer), this detail table then has its own child table again linked by a foreign key (integer).  So I have 3 levels

    In my LINQ quey I can see the first child table but not the second.  The datacontext has the .HasMany property created so it should work.  Can anyone give me an example of a 3 level nested linq query ? Ive tried a standard table join but the 3rd level table is always empty and Ive also played around with .Include but I still cant get it to work

    Wednesday, April 26, 2017 2:54 PM

All replies

  • User-1838255255 posted

    Hi misuk11,

    About this phenomenon, as far as I know, the query result of the 2nd table may be more than one record( in a one-to-many relationship). Because of that, the 3rd table will not be queried directly. therefore, you’d better inquire the result separately to query the 3rd table.

    I have created a simple demo, which includes three entities: Grandpa, Father, and Children. Both of them are the one-to-many relationship.

    By using the following Linq query I can take the record of Children.

    Sample Code:

    StringBuilder result = new StringBuilder();
                Grandpa grandPa = db.Grandpas.Find(1);
                    .ForEach(f => f.Childrens.ToList()
                    .ForEach(c => result.Append(c.ChildrenName+" ")));
                return result.ToString();

    Data and Result:



    If you have other concerns or need further help, please provide more details about your table relationship and the ultimate goal that you want to achieve.


    Best Regards,

    Eric Du

    Thursday, April 27, 2017 9:21 AM
  • User11669696 posted

    try with SelectMany method, for example

    var father = db.Grandpas.SelectMany(g => g.Fathers);
    var children = db.Grandpas.SelectMany(g => g.Fathers).SelectMany(f => f.Childrens);

    It has a similar function to foreach method. That may help you get the 3rd level table

    Friday, April 28, 2017 9:36 AM