I have come across an interesting problem in Entity Framework 6 and SQL Server.
We have a table with a Composite Key. Here is an example;
ID Col1 Col2
-- ---- ----
1 1 1
2 1 2
3 2 1
4 2 2
5 2 3
So, Col2 is unique for each Col1. I have a requirement to swap 2 values to produce this desired result...
ID Col1 Col2
-- ---- ----
1 1 2
2 1 1
I am using Entity Framework, load the object from the database, make my change, and call SaveChanges.
I Receive the exception: "Violation of UNIQUE KEY constraint 'UQ_TableA_Constraint1'. Cannot insert duplicate key in object 'dbo.TableA'."
Supposedly, SaveChanges is called in a transaction. The EF Source seems to indicate it is, and the fact that a failed update is atomic would indicate this is working. However, it also appears that updates are completed ROW BY ROW, even inside the transaction. Thus that EF first performs an update to record 1 which temporarily produces a duplicate unique key.
Is there a manner to mitigate this? I would rather not update to a temp value, call savechanges, and then update to the correct value as this potentially could fail and leave the data in an incorrect state.
Are there any options?