5

I have entity User with a couple of one-to-one and many-to-many relations and Identity primary key, and generic repository which created on each request.

I have an registration form with client and server validation and i decided to turn off client validation to test how server would behave in such case.

I turned off client validation to test the registration form and put some invalid values so i get back form saying that i have some errors, after i fixed that i got 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 entity User but when i found this How to clean-up an Entity Framework object context? so instead detaching only User entity i decided to try to clean object context completely running that 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 all working well and i didn't get Conflicting changes detected error any more, but i am still wondering why such situation was taking place, may be some one may explain?

Community
  • 1
  • 1
Joper
  • 8,019
  • 21
  • 53
  • 80

1 Answers1

0

You may find your answer here:

context.ObjectStateManager.GetObjectStateEntries(System.Data.Entity.EntityState.Added| System.Data.Entity.EntityState.Unchanged);
Pieter
  • 3,339
  • 5
  • 30
  • 63
mez
  • 35
  • 2
  • 1
    Does this answer the question? He specifically asks why this was occurring in the first place, in that his code shouldn't be creating a degenerate state - not how to see what's valid and what isn't. – George R Feb 25 '14 at 02:27