I have an Item. Item has a Category.
Category has ID, Name, Parent
And now for a completely different approach to hierarchical data, for example populating a treeview.
First, do a flat query for all data, and then build the object graph in memory:
var items = this.DbContext.Items.Where(i=> i.EntityStatusId == entityStatusId).Select(a=> new ItemInfo() {
Id = a.Id,
ParentId = a.ParentId,
Name = a.Name,
ItemTypeId = a.ItemTypeId
}).ToList();
Get the root item:
parent = items.FirstOrDefault(a => a.ItemTypeId == (int)Enums.ItemTypes.Root);
Now build your graph:
this.GetDecendantsFromList(parent, items);
private void GetDecendantsFromList(ItemInfo parent, List items)
{
parent.Children = items.Where(a => a.ParentId == parent.Id).ToList();
foreach (var child in parent.Children)
{
this.GetDecendantsFromList(child,items);
}
}