Zulu Khan
Zulu Khan

Reputation: 45

LINQ Parent Child Relationship in an Object

I have the following classes

class Menu
{
  public int Id {get;set;}
  public String Title {get;set;}
  public List<MenuItems> MenuItems {get;set;}
}

class MenuItems
{
  public int id {get;set;}
  public String Title {get;set;}
  public String Address {get;set;} 
}

This application stores a whole set of Menus and MenuItems in Database. These menu items are then assigned to a particular User. The idea is that upon UserLogin, a menubar should be generated dynamically based upon the assigned MenuItems.

I want to store the Results of the LINQ query in a class called UserMenuBar

class UserMenuBar
{
  public int MenuId{get;set;}
  public String MenuTitle {get;set;}
  public List<MenuItems>{get;set;}  // Related MenuItems.. 
}

Here is my LINQ Query,

IEnumerable<UserMenuBar> m= from mnubar in p.Menus
                            join mitems in p.MenuItems
                            on mnubar.MenuItemId equals mitems.id
                            where mnubar.UserId == UName.UserId
                            select new Models.types.UserMenuBar
                            {
                             HeadId=mitems.MenuHeadId,
                             HeadTitle=mitems.MenuHead.MenuTitle
                            }

How do I store the MenuItems in the List.

Any Help would be much appreciated..

Upvotes: 1

Views: 752

Answers (1)

shashwat12
shashwat12

Reputation: 168

If i understand your question correctly, you are having 2 tables, Menu and MenuItems, which are joined together. Menu can have many MenuItems and you want to display this MenuBar based on user credentials.

I would recommed the following data structre

    class Menu
     {
       public int Id{get; set;}
       public String Title{get; set;}
       public List<MenuItems> MenuItems{get; set;}
       public int UserId {get; set;}
     }

    class MenuItem
     {
       public int MenuId{get; set;} // Link to the parent Menu Id
       public int Id{get; set;}
       public int Title{get; set;}
       public string Address{get; set;}
     }

You can have 2 queries to complete your task.

    IEnumerable<UserMenuBar> userMenuBar = from users in Users join
                                            menus in Menus on users.Id
                                             equals menus.UserId
                                              select
                                               {
                                                 MenuId = menus.Id,
                                                 MenuTitle = menus.Title
                                               };

Now populate MenuItems based on Menu.

    userMenuBar.ForEach(
      v => {
             v.MenuItems = (from menuItems in MenuItem
                            where menuItems.MenuId = v.MenuId
                             select menuItems).ToList();
           }
    );

Hope it helps!!!

Upvotes: 1

Related Questions