Entity structure. Conflicting changes detected. This can happen when you try to insert multiple objects with the same key.

I have an entity Userwith two relationships one-to-one, many-to-manyand Identity primary keyand generic repository, that are created for each request.

I have a registration form with client and server verification, and I decided to disable client verification in order to check how the server will behave in this case.

I disabled the client check to test the registration form and put some invalid values ​​to get the feedback form, stating that I have some errors after I fixed that I have a very interesting error saying:

_context.SaveChanges(); //towing the error below:

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

It was strange for me because I detached the object User, but when I found this How to clear the context of an Entity Framework object? so instead of separating only the object User, I decided to try to completely clear the context of the object by running this code:

var objectStateEntries = this.objectContext
                             .ObjectStateManager
                             .GetObjectStateEntries(EntityState.Added);

    foreach (var objectStateEntry in objectStateEntries)
    {
        if(objectStateEntry.Entity != null)
           this.objectContext.Detach(objectStateEntry.Entity);
    }

So, after that, everything works well, and I didn’t get the error anymore Conflicting changes detected, but I’m still wondering why such a situation took place, maybe someone can explain?

+5
source share
1 answer

You can find your answer here :

context.ObjectStateManager.GetObjectStateEntries(System.Data.Entity.EntityState.Added| System.Data.Entity.EntityState.Unchanged);
0
source

All Articles