简体   繁体   中英

how can i disable unique constraints when savechanges in entity framework

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?

I hope I understand your question.
Contraints must be satisfied also inside a transaction, this is a SQL Server (and other DBMSs) behaviour not an EF behaviour.
You can use a temporary value inside a transaction to be sure that everything went well.
If you need to run update queries (on multiple records), you can use an external library https://github.com/loresoft/EntityFramework.Extended (but if I understand your question, you won't solve contraint issues).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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