I have a single database table representing a file tree structure.
Files
- Id (int, primary key)
- Name
- ParentId (int, foreign key to Files.Id)
How can I write a method that makes sure all parents of a child cannot have the child’s Id as its ParentId to prevent a infinite loop when displaying the tree structure.
Also, is there a more efficient way to design this?
Update:
I use sql server 2008 which supports hierarchy id, would that be helpful? (I’m not sure if EF supports it)
You could potentially add a value that is “level” and then you simply need to make sure that no node has a parent that has a level that is greater than or equal to its own. When you add the nodes, you would set the new child node to parent node level + 1.
Cheers