Otis wrote:
It comes down to this (very short description)
you have a hashtable or dictionary, in which you store id-node combinations. You then traverse the set of entities from front to back. for each entity you create a new node and add it to the hashtable. You then use the hashtable to select the parent for the entity and add the node to the parent's node (which you obtain from the hashtable!)'s nodelist.
viola
I'm looking at a similar scenario here as well. Fortunately I'm using SQL 2005 at the back-end so I can use a CTE to do the recursion for me
Basic solution goes something like this:
- Create a CTE that joins from the parent dept id to the dept id
- Select just the id of the dept table (or whatever you might be using) from the CTE
- Wrap that in a stored procedure
- Call the stored procedure to get a list of dept ids
- Fetch your entities by using a FieldCompareRangePredicate, giving it the list of ids
Hey Presto - two hits to the database and away you go.
Now, if you need to reconstruct the hierarchy in code, you can also apply a sort to the CTE to make sure you get the nodes in a sensible order (i.e. starting at the root of the tree and working down) then when you do the fetch you should always (but best to ensure in code!) that you have already got the parent available to you.
Do what Otis suggested (id + node in a dictionary) to make sure you can reconstruct the tree easily.
The benefit of doing it this way is that
a) You don't need to track the root node in the database - which makes updates that bit easier
b) It's dead easy to return partial trees - just tell it what node you want to use as the root, and the CTE will get the bits from there down
Obviously, this only works if your DB supports a CTE-type construct. Oracle does as well (and others, presumably) but it's so long since I used it that i can't remember what it's called...
And, there are myriad discussion on t'internet about which is the better data model to go with. Most that I've seen actually favour the 'store the root node for each node' approach, but somehow i just think that is less elegant. Each to their own, I guess.
Oh, the joys of SQL 2005