Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework 5 - "Conflicting Changes Detected"

In our EF 5 application, when we get a SQL Server deadlock error on an insert or update, we immediately try the operation again. However, when we attempt to do so, we're getting the following error:

"Conflicting changes detected. This may happen when trying to insert multiple entities with the same key."

This error is not coming from SQL Server. This is an EF 5 error. And we are not attempting to insert multiple entities with the same key. IOW, we're not attempting to insert a duplicate row. However, I suspect this error means something else. But I'm not entirely certain I know what the issue is. If I had to guess, I would say that on the first attempt, EF sees where trying to insert an entity. It fails because of a deadlock. When we immediately try again, EF thinks we're trying to do the very same operation again, with the same key, and doesn't like it. Not sure how to get around this.

like image 674
Randy Minder Avatar asked Jun 21 '13 14:06

Randy Minder


1 Answers

It sounds like you might be trying to execute your queries against the same instance of the DbContext. In which case, your changes are already pending from the last try.

Since there is no “undo pending changes” on the context, you must dispose and recreate the context in between “retries”.

like image 187
Jim Avatar answered Sep 23 '22 18:09

Jim