Different types of users in ASP.Net Identity 2.0

So, I'm trying to introduce different users into the application, firstly, let's say that there is only one kind of user:

public class ApplicationUser : IdentityUser { // Other Properties public int TeacherID { get; set; } [ForeignKey("TeacherID ")] public virtual Teacher Teacher { get; set; } } public class Teacher { [Key] public int TeacherID { get; set; } public int UserID { get; set; } // Other properties [ForeignKey("UserID")] public virtual ApplicationUser User { get; set; } } 

There is one single connection between these two objects, but what if there are more than one type of user? I cannot have this ForeignKey in the User entity, I think I will go in the wrong direction.

I’m at least talking about using roles for this, so there is an administrator, teacher, student and different roles for each of them, but what happens if I want to save additional properties for each kind of role?

 public class IdentityUserRole<TKey> { public IdentityUserRole(); // Resumen: // RoleId for the role public virtual TKey RoleId { get; set; } // // Resumen: // UserId for the user that is in the role public virtual TKey UserId { get; set; } } 

I mean, I can extend the IdentityUserRole class and add additional properties, but how to add properties for each kind of role?

+6
source share
1 answer

Of course, it makes sense to use roles for this purpose, but that means you can assign multiple roles. therefore, the user can be a Teacher and a Student, but it can happen.

If you want to add additional properties to the role class, this will be done in the same way as for the user. Create your own version of Role as follows:

 public class ApplicationRole : IdentityRole { public string bool CanJuggle { get; set; } } 

And you will need the RoleManager class:

 public class ApplicationRoleManager : RoleManager<ApplicationRole> { public ApplicationRoleManager(IRoleStore<ApplicationRole> store) : base(store) { } //snip } 

And don't forget that your context should change:

 public class YourContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim> { //snip } 

Think that covers all relevant parts.

+4
source

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


All Articles