Cannot Insert Duplicate Key Row in Object with Unique Index
I Am Trying to Run the Following Query: Update Oar. Oa_Academichead Set Personid=15857 Where Personid=1234 but I Am Getting the Error: Cannot Insert Duplicate...
I am trying to run the following query:
update OAR.oa_AcademicHead
set personid=15857
where personid=1234
but I am getting the error:
Cannot insert duplicate key row in object 'OAR.oa_AcademicHead' with unique index 'IX_oa_AcademicHead_personid'.
The statement has been terminated.
What can be done to fix this??
4 Answers
A row where personid is 15857 already exists in the table. The unique index on that column is preventing you from committing another record with the same personid (an update is really a delete and insert).
You'll have to remove the existing person with that id first before running your query.*
* Disclaimer: make sure this is actually what you want to do; be aware of the issues it might cause.
I am aware that this question is really old. But still might be helpful.
I've experienced this problem with my database and managed to fix it after a few hours of struggling.
My database has an Attachments table, which has primary key ID. I also have messageID column and was not able to create two rows with same messageID. I have found that messageID is indexer. I don't know what are indexers used for exactly, but I simply deleted indexer and now it works fine.
If you get said error while using ASP.NET MVC do something like this:
db.Entry(personObject).State = EntityState.Modified;
db.Entry(personObject).Property(x => x.personid).IsModified = false;
db.SaveChanges();
If your model is decorated with an indexer like [Index(nameof(SomeForeignKey), nameof(SomeOtherForeignKey), IsUnique = true)], then you will counter problems like those, like "An error occurred while updating the entries. See the inner exception for details."