Mehreen
Mehreen

Reputation: 13

SqlException: Cannot insert duplicate key row in object with unique index

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:

AspNetRoles Table Design

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

Answers (1)

Garrison Becker
Garrison Becker

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.

  1. dbo.AspNetRoles is the table where you're attempting to insert a duplicate key row.
  2. RoleNameIndex is the name of the unique index you have on the table that you're violating with your insert.
  3. Teacher is the value of your unique key.

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

Related Questions