lad4bear wrote:
Yip. I've always found hierarchial data to be a pain and I suspect I'm not alone. I know a few people have tried to implement a nested-set using the code generated by llblgen but I don't know if anyone actually succeeded. That's not a criticism of llblgen, I love using it but I would love it more if abstracted away tree management. hehe .. and mult-language support ( i thought i'd just throw that one in case you have some spare time! )
heh spare time...
I'll show you a little trick, which will give you an O(n) routine to build up a tree from a single set of entities. You might already know this, but in case you don't, it might help
Say, you have an Employee entity and it has a reference to itself called 'Manager' and has an FK field called 'ManagerID', which can be null, which means it's the root.
To build the tree from root to leafs, we just have to walk the list twice. One run over the list is for speeding up the retrieval of parent nodes. For small sets this isn't really necessary.
EntityCollection<EmployeeEntity> employees = new EntityCollection<EmployeeEntity>();
using(DataAccessAdapter adapter = new DataAccessAdapter())
{
adapter.FetchEntityCollection(employees, null);
}
Dictionary<int, EmployeeEntity> idToEmployee = new Dictionary<int, EmployeeEntity>();
foreach(EmployeeEntity e in employees)
{
idToEmployee.Add(e.Id, e);
}
EmployeeEntity root = null;
// build the hierarchy
foreach(EmployeeEntity e in employees)
{
if(e.TestCurrentFieldValueForNull(EmployeeFieldIndex.ManagerId))
{
// root
root = e;
continue;
}
EmployeeEntity manager = null;
if(!idToEmployees.TryGetValue(e.ManagerId, out manager))
{
// found an employee with a manager which doesn't exist.
throw new Exception("Please implement FK constraints on the Employee table!");
}
e.Manager = manager;
}
That's it.
You can make this generic by passing in a relation, and other elements to make the function generic instead of dependant on the structure of the entity.