Entity Framework Code First - many-to-many with one class

I have a navigation menu provider that I am trying to move to EF Code First (EF4, CPT5) using a MenuItem object. It is more an exercise to gain the convenience of building a different relationship with EF Code First than anything else.

My MenuItem has a field called SubMenuItems, which is a collection of MenuItems. When I use EF Code First (without changing classes), the table created for MenuItems adds a column for the parent menu item. The menu will be displayed correctly, but this eliminates any possibility of having a menu item in several submenus. What is the correct way to tell EF Code First, so that each MenuItem element is a standalone element and creates another table that links the SubMenuItems of the menu 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 tried to override OnModelCreating, but each attempt ended up either broken, or did the same thing as without me, touching OnModelCreating. I'm sure I'm just "doing it wrong."

Thank!

+3
source
1

Many-to-Many MenuItem, MenuItem :

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

}
+3

Source: https://habr.com/ru/post/1793274/


All Articles