if the tree is dynamic then pull all data into memory and build the tree in business logic rather than db calls.
Some details about this approach:
- Fetch all the entities in one go.
- Store them in a Dictionary or a hashtable. Store the list of child entities for each ParentId.
Example:
Dictionary<int, List<MyEntity>> myDictionary = new Dictionary<int, List<MyEntity>>();
foreach (MyEntity myEntity in MyEntities)
{
List<MyEntity> children;
int parentId = myEntity .ParentId;
if (!myDictionary.TryGetValue(parentId, out children))
{
children = new List<MyEntity>();
myDictionary.Add(parentId, children);
}
if (!children.Contains(myEntity))
{
children.Add(myEntity);
}
}
This way you can easily build a TreeView for instance using a recursive function that queries the Dictionary for the children of each node, starting from 0/null for the root node(s).
public void SomeMethod()
{
TreeView1.Nodes.Clear();
PopulateChildNodes(myDictionary, TreeView1.Nodes, 0);
}
private void PopulateChildNodes(Dictionary<int, List<MyEntity>> myDictionary, TreeNodeCollection childNodes, int parentId)
{
List<MyEntity> children = new List<MyEntity>();
if (myDictionary.TryGetValue(parentId, out children))
{
foreach (MyEntity child in children)
{
TreeNode childNode = new TreeNode(child.Name, child.Id.ToString());
PopulateChildNodes(myDictionary, childNode.ChildNodes, child.Id);
childNodes.Add(childNode);
}
}
}