Add New Role in AspNetRoles Table Identity

Viewed 3947

How to Add New Role in AspNetRoles Table in Identity?

var roleresult = UserManager.AddToRole(currentUser.Id, "Admin");

I am using the above code to assign Admin role to the user, but it throws an error

"Role Admin does not exist."

I have tried to Add Role in AspNetRoles Table directly in the SQL, but failed.

Can anyone please tell me how to add New Role in AspNetRoles Table Using Code?

1 Answers

You need to Add the Role Admin first before adding the User to the Role:

var roleStore = new RoleStore<IdentityRole>(context); //Pass the instance of your DbContext here
var roleManager = new RoleManager<IdentityRole>(roleStore);

Create the Role Admin:

roleManager.Create(new IdentityRole { Name = "Admin" });

Then add your User:

UserManager.AddToRole(currentUser.Id, "Admin");
Related