When calling AcceptChanges I get the following error:
AcceptChanges cannot continue because the object’s key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.
Now I’ve searched the web for quite a bit, but didn’t find the answer I was looking for.
I know they made it by design so that you should prevent from adding an entity that already exists by using the ID instead of an entity object but I’m in a situation where i simply cannot do that.
I have an import and an export, which is generic, I can give any entity object and it will make it an xml format, and in reverse I can give any xml and get the right entity. I couldn’t use a serializer because I had to make the xml in a custom format.
The problem lies when I have deeper nested entities that could have been added to the main entity before already , I cannot check it on the spot so they get added. causing the problem that the same entity might get added multiple times.
And when I’m further ahead and I wish to apply changes, the error happens.
Now consider that I don’t have a choice in the matter of preventing the “adding of the same entity multiple times”-problem and I have to deal with it after they have been added.
How can I delete duplicate entities from the ObjectStateManager, so that I can call apply changes?
Only manually by searching the
ObjectStateManagerand resolving duplicates. That is the reason why you should resolve that issue prior to adding entities toObjectContextor inObjectStateManager.ObjectStateManagerChangedevent handler.Anyway you are asking wrong question. Even if you delete duplicate entities from
ObjectStateManagerit will not solve the problem. Deleting entities will just break your object graphs. You also need to fix all references to deleted entities and point them to single remaining entity instance.This issue is usually handled directly by serialization / deserialization and if you write it yourselves you should do it as well.