Reputation: 4510
So, I'm trying to implement different kind of users on my application, first, let's say there's 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's a one to one relationship between those 2 entities, but what if there's more than one type of user? I can't have that ForeignKey on the User entity, I think I'm going in the wrong direction.
I though about using roles for this, so there's an Admin, a Teacher, an Student, and different kind of roles for each one, but what happens if I want to store extra 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 class IdentityUserRole and add more properties, but how do I add properties for each kind of role?
Upvotes: 6
Views: 1989
Reputation: 118937
It certainly makes sense to use roles for this purpose, but it does mean you could assign multiple roles. so a user could be a Teacher and a Student, but that can happen.
If you want to add extra properties to the role class, it's done in the same way as is done for user. Create your own version of Role
like this:
public class ApplicationRole : IdentityRole
{
public string bool CanJuggle { get; set; }
}
And you need a RoleManager class to go with it:
public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
public ApplicationRoleManager(IRoleStore<ApplicationRole> store)
: base(store)
{ }
//snip
}
And not forgetting your context needs to change:
public class YourContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
{
//snip
}
Think that covers all the relevant parts.
Upvotes: 4