I have the following database design for a menuItem table
Id PId MenuLink
--- --- ---------
1 Null Home.aspx
2 Null Admin.aspx
3 Null Logout.aspx
4 2 Manage Content.aspx
5 2 Manage Users.aspx
6 2 Manage Storage.aspx
7 4 Review Content.aspx
8 4 Add New Content.aspx
9 8 Articles.aspx
10 8 News.aspx
It n level hierarchical menu, Root items have Pid Nil & rest have their parent Ids. Now I have a Business object for this table.
public class myMenuItem
{
public int Id {get; set;}
public int PId {get; set;}
public string MenuLink {get; set;}
}
I want to populate my busienss object in such a way that each MenuItem BO would contain the parent & all its child items (n levels)
Currently I first get the Root item, then populate each level one by one with a separate Business object which I created separately(Duplication). Is there a better way to do this task (as my table is single) ?
public class myMenuItem
{
public int Id {get; set;}
public int PId {get; set;}
public string MenuLink {get; set;}
public List<level1> Level1Items {get ; set;}
public List<level2> Level2Items {get ; set;}
}
// Duplicate class
public class level1
{
public int Id {get; set;}
public int PId {get; set;}
public string MenuLink {get; set;}
// Manually create another list
}
“Recursive” is the word you’re looking for here. Instead of making classes for each level, you’d want just the
myMenuItem, I assume. I’m also going to assume that there isn’t any significance tolevel1andlevel2, that they’re just named like that for uniqueness.So, your
myMenuItemis fine as-is for the example here, except your two lists (Level1ItemsandLevel2Items) should be replaced byList<MenuItem> ChildItems, for example.For the sake of readability with SO’s colouring, I’ve decided to rename
myMenuItemtoMyMenuItem.You could probably do something like this
You’d probably benefit from expanding upon this to instantiate
MyMenuItemalong the way instead of doing it before you build the tree structure.