Search code examples
entity-frameworkobjectstatemanager

How to find out which entity is inside the ObjectStateManager more then once


Hi 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'm trying to fix it but i need to pinpoint what entity is giving me trouble so i know where to look.

i know what the error is and i know how to solve it, but i don't know how to find out which entity is double.


Solution

  • You can check the ObjectStateManager to get all the modified entities. the code goes something like this:

    var lst = context.ObjectStateManager
                  .GetObjectStateEntries(EntityState.Added |
                                         EntityState.Modified | 
                                         EntityState.Deleted);
    var res = lst.GroupBy(c => c.EntityKey).Where(c=> c.Count() > 1);