Question

Hey I have following class:

public class Tree 
{
  public int Id { get; set; }
  public Tree Parent { get; set; }
  public ICollection Chidren { get; set; } 
}

I want to get all of related entities.

My tree structure looks like below:

- Root (id 1)
  -- Cat1 (id 2)
     --SubCat 1 (id 4)
     --SubCat 2 (id 5)
  -- Cat2 (id 3)

If I try to get all entities using:

_context.Entity.FirstOrDefault(x => x.Id == 1)
               .Include(x => x.Children)

it gaves me Root, cat1 and cat2 (as children), but Cat1 and Cat2 childrens are missing. Is it possible to get ALL related entities, starting from root entity, and ending at "children of children"?

1
0
9/12/2017 12:03:33 PM

Popular Answer

Ok i understand.

Like explain here : Understanding .AsEnumerable() in LINQ to SQL

AsEnumerable() and ToList() send the SQL query to database. So you load all datas with all the children objects using SQL side, and then you filter on the ID in the code side.

If you do FirstOrDefault() in the SQL query you'll get only the tree who have id=1 and his first Children.

You can use :

 var tree = _context.Trees
        .Include(x => x.Children)
        .AsEnumerable()
        .FirstOrDefault(x => x.Id == 1);

But be careful, maybe you are loading so many datas and it can be very heavy and slow, depending to the database size.

Otherwise, you can load in 2 times, first the #1 element, and then his children.

1
9/12/2017 1:29:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow