2

My first post on Stackoverflow. So Apologies in advance if I do not understand something here :)

I have a abstract class called ElementEntity. Inside this class i have 2 many to many relations, ChildRelations and ParentRelations.

I need a list with id's from all the Children and grandchildren etc.. form a certain ElementEntity.

We don't know how deep this tree is so somthing like: Context.Hospitals().Include(b => b.ChildRelations).ThenInclude(c => c.child).ThenInclude etc.. is not an option. ( Hospital is a derived ElementEntity )

What would be the best (most inexpensive) approach?

As indication a certain element could have hundreds of thousands of offspring objects.

public abstract class ElementEntity
{
    public long Id {get; set;}

    public virtual ICollection<BaseGroupParentChildRelation> ParentRelations { get; } = new List<BaseGroupParentChildRelation>();
    public virtual ICollection<BaseGroupParentChildRelation> ChildRelations { get; } = new List<BaseGroupParentChildRelation>();

}

public class BaseGroupParentChildRelation 
{
    public long ParentId { get; set; }

    public virtual ElementEntity Parent { get; set; }

    public long ChildId { get; set; }

    public virtual ElementEntity Child { get; set; }
}

Possible fix:

 await projectDbContext.Set<BaseGroupParentChildRelation>().ToListAsync();                    
 var Hotels = await projectDbContext.Hotels.Include(b => 
 b.ChildRelations).ThenInclude(b => b.Child).ToListAsync();

Hotels now include children, grandchildren, great-grandchildren etc.. etc..

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
Emiel
  • 21
  • 2
  • 1
    Unfortunately hierarchical queries are not supported by LINQ and ORMs like EF Core. All custom solutions have drawbacks/limitations, so in case you are targeting concrete database, consider goindg to SQL / SP level and use the database specific hierarchical SQL dialect (usually CTE). – Ivan Stoev Dec 05 '18 at 13:59
  • 1
    I'm not entirely sure, but I think hierarchies are handled naturally via EF's object fixup. Once you include the first level. That query basically pulls in all the entities for all levels and EF adds them to the appropriate collections. You'll need to test it obviously. – Chris Pratt Dec 05 '18 at 14:57
  • @ChrisPratt What you are suggesting works only when you [load the whole table](https://stackoverflow.com/questions/46160780/map-category-parent-id-self-referencing-table-structure-to-ef-core-entity/46161259#46161259) – Ivan Stoev Dec 05 '18 at 19:18

0 Answers0