Entity Framework 6 SaveChanges causes unique constraint exception

c# entity-framework-6

Question

I'm getting a unique constraint violation when trying to do SaveChanges() on my EF.

There are two columns, ID and Order. 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! 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)

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

As I said though, when I do SaveChanges() I get an exception.

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?). The problem seems to me to be that "it" isn't doing the update correctly.

Appreciate any help!

1
1
9/15/2015 7:05:49 AM

Accepted Answer

EntityFramework updates one row at a time. So by switching the Order value of the two objects and calling SaveChanges() It first fires something like this:

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.

3
9/15/2015 8:05:15 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow