3

I have a navigation menu provider that I am trying to move over to EF Code First (EF4, CPT5) using a MenuItem object. This is more of an exercise to get comfortable with building different relationships with EF Code First than anything else.

My MenuItem has a field called SubMenuItems that is a collection of MenuItems. When I use EF Code First (without modifying the classes) the table that is created for the MenuItems adds a column for the parent menu item. The menu will display properly, but this removes any ability to have a menu item appear in more than one sub menu. What is the proper way to tell EF Code First that I want each MenuItem to be a standalone item and to create another table that links a menu item's SubMenuItems to other MenuItems?

public class MenuItem
{
    public int ID { get; set; }
    public virtual SubMenuItems { get; set; }
    public string Text { get; set; }
    public string Controller { get; set; }
    public string Action { get; set; }
    public bool IsRoot { get; set; }
    public bool RequiresAuthentication { get; set; }
    public virtual ICollection<MenuPermission> RequiredPermissions { get; set; }
    public bool HiddenIfAuthenticated { get; set; }
    public int DisplayOrder { get; set; }
}

...

public class MyDbContext : DbContext
{
    public DbSet<MenuItems> MenuItems { get; set; }
    public DbSet<MenuItemPermission> MenuItemPermissions { get; set; }
    ...
}

I have attempted to override OnModelCreating but each attempt ended in either being broken or doing the exact same thing that it does without me touching OnModelCreating. I'm sure I'm just "doing it wrong."

Thanks!

Jim D'Angelo
  • 3,952
  • 3
  • 25
  • 39

1 Answers1

3

You need to setup a Many-to-Many Self Referencing Association for MenuItem entity so that each MenuItem could have multiple Parent Items:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<MenuItem>()
                .HasMany(m => m.SubMenuItems)
                .WithMany();

}
Morteza Manavi
  • 33,026
  • 6
  • 100
  • 83
  • I thought I did that already, but I guess I had something messed up. Thank so much, that worked out perfectly! – Jim D'Angelo Feb 19 '11 at 23:26
  • and if your join table has different column/table names -- http://stackoverflow.com/a/12331031/1037948 – drzaus Jun 13 '13 at 17:44
  • This method should be added to your class inheriting from `DbContext`. In EF6, the parameter should be of type `DbModelBuilder`. – Peppe L-G Sep 05 '15 at 15:33