SQL 无法在具有唯一索引的对象中插入重复的键行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22209734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot insert duplicate key row in object with unique index
提问by user3325454
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??
可以做些什么来解决这个问题?
回答by C???
A row where personidis 15857already 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).
一排,其中personid是15857已经存在于表。该列上的唯一索引阻止您提交另一条相同的记录personid(更新实际上是删除和插入)。
You'll have to remove the existing person with that id first before running your query.*
在运行查询之前,您必须先删除具有该 ID 的现有人员。*
* Disclaimer: make sure this is actually what you want to do; be aware of the issues it might cause.
* 免责声明:确保这确实是您想要做的;注意它可能导致的问题。
回答by Colin
If you get said error while using ASP.NET MVC do something like this:
如果您在使用 ASP.NET MVC 时遇到上述错误,请执行以下操作:
db.Entry(personObject).State = EntityState.Modified;
db.Entry(personObject).Property(x => x.personid).IsModified = false;
db.SaveChanges();

