2
votes

I have read information about how to extend Identity with and additional fields, connected to the user's profile.

But I can not understand how to extend Identity functionality by adding a table, connected with Roles.

What I want to do:

  1. My MVC application should consists of some sub-applications.
  2. I want users to be identified by roles and redirected to the needed sub-application.
  3. Inside sub-application they can have different roles (admin, user, etc.)
  4. So all roles are listed in the Identity Role table (AspNetRoles).
  5. Now I need to add to AspNetRoles one extra field, that points to the new table with the sub-application names.

The new class of sub-application is:

public class Project 
{
    public int ID { get; set; }

    [StringLength(100)]
    public string ProjectName { get; set; }

   // How can the foreign key to AspNetRoles be added  ?    
}

Can you help to add a foreign key to AspNetRoles table, please?

1

1 Answers

2
votes

John Atten has written an extraordinary blog post about this topic. What's the general idea?

You create a sub-class of the IdentityRole class and add your Project class as a property to create the relationship. The code could look somewhat similar to the following:

public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }

    public ApplicationRole(string name) : base(name)
    {
    }

    public virtual Project Project { get; set; }
}

In the section Extending the Identity Role Class he also shows what you have to do next in your DbContext (look at the implementation of the OnModelCreating method). That's not necessary in some cases. If you use the generic implementation of IdentityDbContext you can pass your role implementation as a type parameter. Drawback is that you normally also have to implement the other type parameters (in most cases just creating a sub-class of the base class used for the type parameter).

In general I like the way how John is creating the whole thing, because it gives you a lot more control compared to the way working with generics. You should read the article to the end, because he explains important concepts in good detail.