Search code examples
c#entity-frameworkef-code-firstasp.net-membershipasp.net-identity

Membership code-first - Add FK to IdentityRole without extending class


As the title says, I'd like to add a FK to Membership's IdentityRole without extending/deriving class:

I have:

 public class ApiController
    {
    [Key]
    public int ApiControllerId { get; set; }
    public ICollection<IdentityRole> Roles { get; set; }

I would like to add

public ICollection<ApiController> Controllers { get; set; }

to Membership's IdentityRole class so EF creates a many-many relationship table (ie ApiControllerRoles)

I have done my homework and I know how to do this (normally) except I don't actually have class definition for IdentityRole in my project. Any idea how I could add this foreign key without the class definition or better yet, how I could go about getting a copy of this class?

Thanks!


Solution

  • Create your ApplicationRole Entity base on IdentityRole

    public class ApplicationRole : IdentityRole
    {
          ...
          public ICollection<ApiController> Controllers { get; set; }
    }
    
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Role, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
    {
          public ApplicationDbContext(): base("DefaultConnection") {}
    }
    
    public class ApiController
    {
            [Key]
            public int ApiControllerId { get; set; }
            public ICollection<ApplicationRole> Roles { get; set; }