question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Support for querying a hierarchy of self-referencing entities?

See original GitHub issue

Hi,

Often you need to retrieve a whole hierarchy of self-referencing entities.

Consider this example:

public class Affiliate
{
  public int Id { get; set; }
  public string Name { get; set; }
  //The person who referred the current one
  public in ReferrerId { get; set; }
  [ForeignKey(nameof(ReferrerId)]
  public Affiliate Referrer { get; set; }
  //People the current has referred
  public virtual ICollection<Affiliate> Referred { get; set; } = new HashSet<Affiliate>();
}

Now I want to retrieve an Affiliate along with its children, grandchildren, and great grandchildren. Or I want to retrieve an Affiliate with its Referrer, he’s referrer’s referrer, and his referrer’s referrer’s referrer n levels up.

How can this be achieved in a single round-trip without involving stored-procedures?

  • Can Linq Expressions be used for this?
  • Is there a repo for that?
  • Anything for EF6?

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:18 (12 by maintainers)

github_iconTop GitHub Comments

6reactions
mdczaplickicommented, Feb 22, 2018

@alvaromongon this actually helped me, you just need to be careful not to create a loop in db. I have made these methods in my UnitOfWork:

public void LoadAllSubordinates(ref User user)
{
    this.LoadSubordinates(user);
}

private void LoadSubordinates(User user)
{
    this.context.Entry(user).Collection(u => u.DirectSubordinates).Load();
    foreach (var userDirectSubordinate in user.DirectSubordinates)
    {
        this.LoadSubordinates(userDirectSubordinate);
    }
}
2reactions
sophismacommented, Aug 9, 2018

I know this thread is old but it pointed me in the right direction. I’m just posting this in case it helps other people. I had an issue where I had an hierarchy of categories of products, for instance, Storage->Internal Storage->SSD, and I had to retrieve the entire hierarchy from a child. The examples posted here were recursive, which can take a performance hit. You can do it iteratively this way:

        public Category GetById(int id)
        {
            var category = this.ObjectSet.FirstOrDefault(e => e.Id == id);

            this.IncludeParentCategories(category);

            return category;
        }

        private void IncludeParentCategories(Category category)
        {
            var currentCategory = category;

            do
            {
                this.UnitOfWork.Context.Entry(currentCategory).Reference(e => e.ParentCategory).Load();
                currentCategory = currentCategory.ParentCategory;
            }
            while (currentCategory != null);
        }
Read more comments on GitHub >

github_iconTop Results From Across the Web

N1QL query with Self Referencing Hierarchy
In this article, I will discuss how traditional RDBMS handles hierarchical queries. The challenges that it has to deal with, and how this...
Read more >
loading a full hierarchy from a self referencing table with ...
Can anyone help me out by giving me some code how to load the full table (e.g. into memory in an optimal scenario...
Read more >
ToSelfHierarchyList
The ToSelfHierarchyList method extend your Entity Framework DbContext to let you easily include a self hierarchy relationship.
Read more >
Define and query hierarchical data with Microsoft Dataverse
With Microsoft Dataverse, hierarchical data structures are supported by self-referential one-to-many (1:N) relationships of the related rows.
Read more >
Modeling self-referencing associations with Hibernate
When you model a hierarchical data structure, you often have to use self-referencing associations. Both ends of these associations are of the same...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found