Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add New Role in AspNetRoles Table Identity

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?

like image 264
Umair Arif Avatar asked Sep 09 '25 14:09

Umair Arif


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");
like image 155
Willy David Jr Avatar answered Sep 13 '25 03:09

Willy David Jr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!