Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework Traverse and return child records in self reference table
    primarykey
    data
    text
    <p>I am using Entity Framework and have a table of BusinessUnits which can reference another record of the same type to form a child-parent hierarchy.</p> <p>I also have a set of users, and user permissions, where each user defined in this table should have access to the BusinessUnit and all sub-business units in the hierarchy. Users should not have access to the BusinessUnit above the one referenced (if exists).</p> <p>How can I go about forming LINQ queries to handle this self-referencing relationship tree and return all the business units (with child units) for which this user has access? Is it possible to do it in one query, or do I need to manually build the tree myself with a for-loop?</p> <p>I have seen schema's reference in this way from node to parent, does this mean I have to start at the furthest child node to build the tree by one parent at a time?</p> <p>Thanks in advance,</p> <p>Chris</p> <pre><code>class BusinessUnit { int BusinessUnitID {get;set;} public string BusinessName {get;set;} BusinessUnit ParentBusinessUnit {get;set;} } class User { int UserID {get;set;} string Firstname {get;set;} } class UserPermissions { [Key, ForeignKey("BusinessUnit"), Column(Order = 0)] BusinessUnit BusinessUnit {get;set;} [Key, ForeignKey("User"), Column(Order = 1)] User User {get;set;} } IEnumerable&lt;BusinessUnit&gt; GetUnitsForWhichUserHasAccess(User user) { /* Example 1 given: BusinessUnitA (ID 1) -&gt; BusinessUnitB (ID 2) -&gt; BusinessUnitC (ID 3) with user with ID 1: and UserPermissions with an entry: BusinessUnit(2), User(1) the list { BusinessUnitB, BusinessUnitC } should be returned */ /* Example 2 given: BusinessUnitA (ID 1) -&gt; BusinessUnitB (ID 2) -&gt; BusinessUnitC (ID 3) with user with ID 1: and UserPermissions with an entry: BusinessUnit(1), User(1) the list { BusinessUnitA, BusinessUnitB, BusinessUnitC } should be returned */ } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload