I can’t seem to get my head around this. I need to build some test data to build a tree menu, but I either get a stackverflow error because it just keeps going or I only get the first level of children. Here is the code I currently have:
private MenuItem _menuItem;
private int _start = 1;
private const int Stop = 5;
public void BuildMenu()
{
var numberOfChildren = new Random((int) DateTime.Now.Ticks).Next(3, 40);
AutoMapper.Mapper.CreateMap<MenuItem, MenuItemDto>().ConvertUsing<MenuItemConverter>();
_menuItem = new MenuItem() {Id = Guid.NewGuid(), Name = "Main Menu"};
_menuItem.ChildMenuItems = BuildChildItems(_menuItem, numberOfChildren);
var menuDto = AutoMapper.Mapper.Map<MenuItem, MenuItemDto>(_menuItem);
}
public ICollection<MenuItem> BuildChildItems(MenuItem parentMenuItem, int numberOfChildren)
{
var childItems = new Collection<MenuItem>();
_start += 1;
for (var i = 0; i <= numberOfChildren; i++)
{
var childItem = new MenuItem()
{
Id = Guid.NewGuid(),
ParentItemId = parentMenuItem.Id,
Parentitem = parentMenuItem,
Name = "Child Menu Item " + DateTime.Now
};
if (_start != Stop)
{
childItem.ChildMenuItems = BuildChildItems(childItem, numberOfChildren);
}
childItems.Add(childItem);
}
return childItems;
}
public class MenuItem
{
public Guid Id { get; set; }
public string Name { get; set; }
public Guid? ParentItemId { get; set; }
public MenuItem Parentitem { get; set; }
public ICollection<MenuItem> ChildMenuItems { get; set; }
}
While this works, you will notice the _start and Stop variables. I put those in so I don;t get a stackoverflow, but obviously that is why I only get the 1st level of each with populated children. I figure I would need to track what level I am in, but not sure how to keep track of it. Not sure why I am drawing a blank today….
This gives the idea rather than actually looking at your specific object model! Have an int which represents the number of levels you want to go to. Send this into the method, decrement it on each recurse until it is zero.