Asp.Net core MVC6 How to initially add roles in Identity 3

si2030 picture si2030 · Apr 23, 2016 · Viewed 12.7k times · Source

I've looked for this in Stackoverflow and so far it appears there are plenty of questions on adding roles in Identity 1 & 2 but its different in Identity 3.

I want to seed roles in the database. I have just two. I intended to use _roleManager which I have injected into the class. Thats fine. My problem is.. there doesnt appear to be any method to actually add a role.. Using CreateAsync is for adding the user to the role.. how do you code to add a role using "_userManager" or do you have to do it another way?

Answer

jamiedanq picture jamiedanq · Apr 23, 2016

EDIT

Identity

In Identity RoleManager is for creating roles and UserManager is for adding users to roles. This is an example to point you in the right direction. The code below is for creating a new role Administrator

if (!roleManager.RoleExists("Administrator"))
            {
                MyIdentityRole newRole = new MyIdentityRole("Administrator", "Administrators can do something with data");
                roleManager.Create(newRole);
            }  

EDIT

Further, this is for adding a user to a role and this also an example:

 \\assuming you test if the user has been assigned to the role "Administrator" before adding them to that role

 if(RoleAdministrator == true){
           userManager.AddToRole(User.Id, "Administrator");
       }