How do I create an NxN relationship in the IdentityRole class with a class I created?

2

I have an automatic mapping of Controllers and its Actions that I execute at application startup (file Global.asax ).

I use this to give the user permission to the given Controller x Action if he has that combination of access rights. Controller + Action + Role .

I need to create the MenuItem x Roles relationship. But I do not know how to add this in the application. It will be a N x N relationship.

Then I have the following:

public class MenuItem
{
    public MenuItem {  
        Roles = new HashSet<IdentityRole>();
    }

    [Key]
    public int Id { get; set; }

    [StringLength(40)]
    [Required(AllowEmptyStrings = false]
    public string Name { get; set; }

    [Required]        
    [ForeignKey("Menu")]
    public int MenuId { get; set; }
    public virtual Menu Menu { get; set; }

    [InverseProperty("MenuItems")]
    public virtual ICollection<IdentityRole> Roles { get; set; }
}

Then I tried:

namespace Microsoft.AspNet.Identity.EntityFramework
{
    public partial class IdentityRole
    {
        public IdentityRole {
            MenuItems = new HashSet<MenuItem>();
        }

        [InverseProperty("Roles")]
        public virtual ICollection<MenuItem> MenuItems { get; set; }
    }
}

However, Visual Studio complains of some error in some parts of the code saying that the IdentityRole class exists in both Microsoft.AspNet.Identity.EntityFramewrk and App.Domain (where my application classes are).

I also tried

Exclude the partial class of IdentityRole and left the MenuItem class with the declared navigation property like this:

public class MenuItem
{
    ...

    public virtual ICollection<IdentityRole> Roles { get; set; }
}

However, by doing this EF creates a MenuItem_Id field within the Roles ( AspNetRoles ) table, meaning as a 1 x N relationship.

How do you create this relationship?

    
asked by anonymous 30.09.2014 / 00:46

1 answer

2

With the indication of Gypsy was easy to solve.

I created a second class of IdentityRole , I added the relationship I need and I started using this class instead of IdentityRole .

So:

public class Role : IdentityRole
{
    public Role() {
        MenuItems = new HashSet<MenuItem>();
    }

    [InverseProperty("Roles")]
    public virtual ICollection<MenuItem> MenuItems { get; set; }
}

And I started to use it:

public class MenuItem
{
    public MenuItem() {
        Roles = new HashSet<MenuItem>();
    }

    [InverseProperty("MenuItems")]
    public virtual ICollection<Role> Roles { get; set; }
}

And then a table for the NxN relationship was created and the module is working.

    
30.09.2014 / 01:15