简体   繁体   English

实体框架6 SaveChanges导致唯一约束异常

[英]Entity Framework 6 SaveChanges causes unique constraint exception

I'm getting a unique constraint violation when trying to do SaveChanges() on my EF. 当我尝试在我的EF上执行SaveChanges() ,我遇到了一个唯一的约束违规。

There are two columns, ID and Order . 有两列, IDOrder The unique constraint is on those two columns. 唯一约束是在这两列上。

I'm updating the order (swapping two of the values). 我正在更新订单(交换两个值)。

However, when I do SaveChanges() I get a DBUpdateExcception saying I've violated the unique constraint - but I haven't! 但是,当我执行SaveChanges()我得到一个DBUpdateExcception说我违反了唯一约束 - 但我没有! I've just swapped the order . 我刚换了订单

Name | ID | Order
BH   | 49 | 1
JK   | 49 | 2

So in code, it now looks like this (and I've checked the EF in the debugger) 所以在代码中,它现在看起来像这样(我在调试器中检查了EF)

Name | ID | Order
BH   | 49 | 2
JK   | 49 | 1

As I said though, when I do SaveChanges() I get an exception. 正如我所说,当我做SaveChanges()我得到一个例外。

I don't know if there is a problem with my model in visual studio 2015 (have to set a property or something to allow updates?). 我不知道我的模型在Visual Studio 2015中是否有问题(必须设置属性或允许更新的东西?)。 The problem seems to me to be that "it" isn't doing the update correctly. 在我看来,问题是“它”没有正确地进行更新。

Appreciate any help! 感谢任何帮助!

EntityFramework updates one row at a time. EntityFramework一次更新一行。 So by switching the Order value of the two objects and calling SaveChanges() It first fires something like this: 因此,通过切换两个对象的Order值并调用SaveChanges()它首先触发这样的事情:

UPDATE TABLENAME SET [Order] = 2 WHERE [TABLENAME].[ID] = 49 AND [TABLENAME].[Order] = 1

If this update would be executed, you would have two rows in the table with the same values in the unique constraint. 如果将执行此更新,则表中将有两行在唯一约束中具有相同的值。 This is why you get the error. 这就是你得到错误的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM