Last post Apr 28, 2017 09:36 AM by Hayley_244
Apr 26, 2017 02:54 PM|misuk11|LINK
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
Apr 27, 2017 09:21 AM|Eric Du|LINK
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.
StringBuilder result = new StringBuilder();
Grandpa grandPa = db.Grandpas.Find(1);
.ForEach(f => f.Childrens.ToList()
.ForEach(c => result.Append(c.ChildrenName+" ")));
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.
Apr 28, 2017 09:36 AM|Hayley_244|LINK
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