1

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"?

bielu000
  • 1,027
  • 1
  • 12
  • 31
  • Check some of the answers here: https://stackoverflow.com/questions/24022957/entity-framework-how-to-disable-lazy-loading-for-specific-query – Ric Sep 12 '17 at 12:05
  • Possible duplicate of [Implementing recursive property loading in EF Core](https://stackoverflow.com/questions/40987365/implementing-recursive-property-loading-in-ef-core) – Federico Dipuma Sep 12 '17 at 12:07
  • If this is the whole tree, you can adopt the solution from https://stackoverflow.com/questions/46160780/map-category-parent-id-self-referencing-table-structure-to-ef-core-entity/46161259#46161259. Something like `_context.Entity.Include(x => x.Children).ToList().FirstOrDefault(x => x.Parent == null);` – Ivan Stoev Sep 12 '17 at 12:14

1 Answers1

1

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.

GGO
  • 2,700
  • 3
  • 16
  • 35