asp.netasp.net-mvcasp.net-coreasp.net-identity

How to implement IdentityRole with custom properties into UserManager?


My IdentityRole:

    public class Trainer : IdentityRole
    {
        public string? Specialization { get; set; }
        public ICollection<Course>? Courses { get; set; }
    }

Example of Admin (not customized role)

                    await userManager.CreateAsync(newAdminUser, "Coding228-");
                    await userManager.AddToRoleAsync(newAdminUser, UserRoles.Admin);

But how to implement Trainer. How to use CreateAsync for it.

I tried this:

                 await userManager.CreateAsync(newTrainer, "Coding228-");
                 await userManager.AddToRoleAsync(newTrainer, Trainer);

but i cant use type "Trainer" is there any possible way to use IdentityRole that i created


Solution

  • How to implement IdentityRole with custom properties into UserManager? But I cant use type "Trainer" is there any possible way to use IdentityRole that I created

    Well,if you look at the implementation details of AddToRoleAsync method within UserManager it has two overload methods one takes a string type of role and another takes a IEnumerable of role as you can see below:

    enter image description here

    Therefore, we cannot append or insert complex object of Trainer (Type of role) becuase AddToRoleAsync must need a string of role or IEnumerable of role, so you cannot do that, it must be the direct role name not class type of anything.

    I am not quite sure why you would like to do that. But this the way of passing parameter for AddToRoleAsync method in order to create new role.

    If have any specific thought why you are trying to do that, you could share that so that we could think if there's any alternative or better way available. But for assigning role, we need to pass either role name or role collection to that method no other overload method available at this moment.

    Note: please refer to this official document for reference.