So I have a SQL table which is basically
ID, ParentID, MenuName, [Lineage, Depth]
The last two columns are auto-computed to help with searching so we can ignore them for now.
I’m creating a drop down menu system with multiple categories.
Unfortunately EF I don’t think plays nice with Self referencing tables more than 1 level deep. So I’m left with a few options
1) Create query, order by depth and then create a custom class in C#, populating it one depth at a time.
2) Find some way to eager load the data in EF, I don’t think it is possible for an unlimited amount of levels, only a fixed amount.
3) Some other way I’m not even sure about.
Any inputs would be welcomed!
I have successfully mapped hierarchical data using EF.
Take for example an
Establishmententity. This can represent a company, university, or some other unit within a larger organizational structure:Here is how the Parent / Children properties are mapped. This way, when you set the Parent of 1 entity, the Parent entity’s Children collection is automatically updated:
Note that so far I haven’t included your Lineage or Depth properties. You are right, EF doesn’t work well for generating nested hierarchical queries with the above relationships. What I finally settled on was the addition of a new gerund entity, along with 2 new entity properties:
While writing this up, hazzik posted an answer that is very similar to this approach. I’ll continue writing up though, to provide a slightly different alternative. I like to make my Ancestor and Offspring gerund types actual entity types because it helps me get the Separation between the Ancestor and Offspring (what you referred to as Depth). Here is how I mapped these:
… and finally, the identifying relationships in the Establishment entity:
Also, I did not use a sproc to update the node mappings. Instead we have a set of internal commands that will derive / compute the Ancestors and Offspring properties based on the Parent & Children properties. However ultimately, you end up being able to do some very similar querying as in hazzik’s answer:
The reason for the bridge entity between the main entity and its Ancestors / Offspring is again because this entity lets you get the Separation. Also, by declaring it as an identifying relationship, you can remove nodes from the collection without having to explicitly call DbContext.Delete() on them.