Reputation: 13
I get this error:
SqlException: Cannot insert duplicate key row in object 'dbo.AspNetRoles' with unique index 'RoleNameIndex'. The duplicate key value is (Teacher). The statement has been terminated.
I am trying to add multiple roles for single users and in my database table AspNetRoles
, I use unique RoleNameIndex
key. Below is a screenshot of the AspNetRoles
table:
Now, each user in my AspNetUsers table is assigned a role. I want to add another role to a user, but keep getting that error. What should I do? Help me with the code please.
My code uses input textbox for User ID and combobox for loading the Role Names. My code,on button click, is as follows:
var newRole = RolecomboBox.Text;
var idnum = Int32.Parse(IdTxtArea.Text);
var item = _db.AspNetUserRoles.FirstOrDefault(w => w.UserId == idnum);
item.AspNetRole.Name = newRole;
Upvotes: 0
Views: 8592
Reputation: 482
The information you need for the solution to your question is all in the SqlException that you were given.
SqlException: Cannot insert duplicate key row in object 'dbo.AspNetRoles' with unique index 'RoleNameIndex'. The duplicate key value is (Teacher). The statement has been terminated.
I bolded the 3 pieces of information you need.
In order to insert additional rows into your dbo.AspNetRoles table for "Teacher", you need to delete the unique index RoleNameIndex, as this is REQUIRING the Name column to be unique.
Upvotes: 2