An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key

74,080

Solution 1

Edit: Original answer used Find instead of Local.SingleOrDefault. It worked in combination with @Juan's Save method but it could cause unnecessary queries to database and else part was probably never executed (executing the else part would cause exception because Find already queried the database and hadn't found the entity so it could not be updated). Thanks to @BenSwayne for finding the issue.

You must check if an entity with the same key is already tracked by the context and modify that entity instead of attaching the current one:

public override void Update(T entity) where T : IEntity {
    if (entity == null) {
        throw new ArgumentException("Cannot add a null entity.");
    }

    var entry = _context.Entry<T>(entity);

    if (entry.State == EntityState.Detached) {
        var set = _context.Set<T>();
        T attachedEntity = set.Local.SingleOrDefault(e => e.Id == entity.Id);  // You need to have access to key

        if (attachedEntity != null) {
            var attachedEntry = _context.Entry(attachedEntity);
            attachedEntry.CurrentValues.SetValues(entity);
        } else {
            entry.State = EntityState.Modified; // This should attach entity
        }
    }
}  

As you can see the main issue is that SingleOrDefault method needs to know the key to find the entity. You can create simple interface exposing the key (IEntity in my example) and implement it in all your entities you want to process this way.

Solution 2

I didn't want to pollute my auto generated EF classes by adding interfaces, or attributes. so this is really a little bit from some of the above answers (so credit goes to Ladislav Mrnka). This provided a simple solution for me.

I added a func to the update method that found the integer key of the entity.

public void Update(TEntity entity, Func<TEntity, int> getKey)
{
    if (entity == null) {
        throw new ArgumentException("Cannot add a null entity.");
    }

    var entry = _context.Entry<T>(entity);

    if (entry.State == EntityState.Detached) {
        var set = _context.Set<T>();
        T attachedEntity = set.Find.(getKey(entity)); 

        if (attachedEntity != null) {
            var attachedEntry = _context.Entry(attachedEntity);
            attachedEntry.CurrentValues.SetValues(entity);
        } else {
            entry.State = EntityState.Modified; // This should attach entity
        }
    }
}  

Then when you call your code, you can use..

repository.Update(entity, key => key.myId);

Solution 3

You can actually retreive the Id through reflection, see example below:

        var entry = _dbContext.Entry<T>(entity);

        // Retreive the Id through reflection
        var pkey = _dbset.Create().GetType().GetProperty("Id").GetValue(entity);

        if (entry.State == EntityState.Detached)
        {
            var set = _dbContext.Set<T>();
            T attachedEntity = set.Find(pkey);  // access the key
            if (attachedEntity != null)
            {
                var attachedEntry = _dbContext.Entry(attachedEntity);
                attachedEntry.CurrentValues.SetValues(entity);
            }
            else
            {
                entry.State = EntityState.Modified; // attach the entity
            }
        }

Solution 4

@serj-sagan you should do it in this way:

**Note that YourDb should be a class derived from DbContext.

public abstract class YourRepoBase<T> where T : class
{
    private YourDb _dbContext;
    private readonly DbSet<T> _dbset;

    public virtual void Update(T entity)
    {
        var entry = _dbContext.Entry<T>(entity);

        // Retreive the Id through reflection
        var pkey = _dbset.Create().GetType().GetProperty("Id").GetValue(entity);

        if (entry.State == EntityState.Detached)
        {
           var set = _dbContext.Set<T>();
           T attachedEntity = set.Find(pkey);  // access the key
           if (attachedEntity != null)
           {
               var attachedEntry = _dbContext.Entry(attachedEntity);
               attachedEntry.CurrentValues.SetValues(entity);
           }
           else
           {
              entry.State = EntityState.Modified; // attach the entity
           }
       }
    }

}

Solution 5

Another solution (based on @Sergey's answer) could be:

private void Update<T>(T entity, Func<T, bool> predicate) where T : class
{
    var entry = Context.Entry(entity);
    if (entry.State == EntityState.Detached)
    {
        var set = Context.Set<T>();
        T attachedEntity = set.Local.SingleOrDefault(predicate); 
        if (attachedEntity != null)
        {
            var attachedEntry = Context.Entry(attachedEntity);
            attachedEntry.CurrentValues.SetValues(entity);
        }
        else
        {
            entry.State = EntityState.Modified; // This should attach entity
        }
    }
}

And then you would call it like this:

Update(EntitytoUpdate, key => key.Id == id)
Share:
74,080
Juan
Author by

Juan

Updated on July 05, 2022

Comments

  • Juan
    Juan almost 2 years

    Using EF5 with a generic Repository Pattern and ninject for dependency injenction and running into an issue when trying to update an entity to the database utilizing stored procs with my edmx.

    my update in DbContextRepository.cs is:

    public override void Update(T entity)
    {
        if (entity == null)
            throw new ArgumentException("Cannot add a null entity.");
    
        var entry = _context.Entry<T>(entity);
    
        if (entry.State == EntityState.Detached)
        {
            _context.Set<T>().Attach(entity);
            entry.State = EntityState.Modified;
        }
    }
    

    From my AddressService.cs which goes back to my repository I have:

     public int Save(vw_address address)
    {
        if (address.address_pk == 0)
        {
            _repo.Insert(address);
        }
        else
        {
            _repo.Update(address);
        }
    
        _repo.SaveChanges();
    
        return address.address_pk;
    }
    

    When it hits the Attach and EntityState.Modified it pukes with the error:

    An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

    I have looked through many of the suggestions in stack and on the Internet and not coming up with anything that resolves it. Any work arounds would be appreciated.

    Thanks!

  • Juan
    Juan over 11 years
    Thanks. So i created an interface IEntity with int Id { get; set; } then tried to do public override void Update(T entity) where T : IEntity but its not liking the where T : IEntity. This is in a repository class ie public class DbContextRepository<T> : BaseRepository<T> where T : class if that makes a difference. Thanks!
  • Ladislav Mrnka
    Ladislav Mrnka over 11 years
    In such case put the constraint directly on class definition
  • Juan
    Juan over 11 years
    hmm.. still not having much luck. I wonder if its because I am using an edmx model. But I am unable to put the constraint directly on the class as it implements BaseRepository and IRepository. Plus in the edmx the entities are coming from views and the primary keys are something like address_pk.
  • patryk.beza
    patryk.beza over 11 years
    I had similar problem (still not solved). The problems are virtual reference-type variables properties which don't update.
  • M.Stramm
    M.Stramm about 11 years
    You seem to completely miss the fact that the OP wants to do this with a generic repository.
  • BenSwayne
    BenSwayne over 10 years
    @LadislavMrnka: When you use set.Find() if it is not already in the object state manager it will be loaded from the db, right? So in the above code attachedEntity will always be not null and you will never attach the passed in entity? (ie: you will never reach the else { statement) Perhaps I am misunderstanding the documentation for DbSet<>.Find(). Should we not be using DbSet<>.Local?
  • Ladislav Mrnka
    Ladislav Mrnka over 10 years
    @BenSwayne: You are right. The code above doesn't reach else part if the entity exists in the database and if it doesn't it will fail because in such case else part must set the state to Added or simply add entity to the set. Using Local will fix it - I will modify the answer.
  • Stay Foolish
    Stay Foolish over 10 years
    @LadislavMrnka: when the attachedEntry is null, should that call the _context.Set<T>().Attach(entity); to attach the entity first before setting the state? or it is what the comment about?
  • Joseph Woodward
    Joseph Woodward over 10 years
    @SerjSagan You can simply do _dbContext.Set<T>().Create().GetTy..
  • Alan Macdonald
    Alan Macdonald about 10 years
    It's worth knowing that the copying over of values between entities will not copy over fields marked as [NotMapped]. This breaks what I want to do.
  • mhesabi
    mhesabi about 10 years
    What if you can't guess what is the entity Primary key name? here e => e.Id == entity.Id
  • Bellash
    Bellash over 9 years
    @mhesabi You may need to add the predicate as second param public virtual void Update(T entity,Func<T, bool> predicate)where T : IEntity { //---hidden T attachedEntity = set.Local.SingleOrDefault(predicate); // So You don't need to have access to key if (attachedEntity != null) {} } }
  • Leon van der Walt
    Leon van der Walt about 9 years
    @LadislavMrnka note that testing Set<T>().Local will not find entities that were removed via Set<T>().Remove() - although they will still be attached
  • Reuel Ribeiro
    Reuel Ribeiro almost 7 years
    Should you be not using set.Local.Find instead of set.Find? I believe your code will always hit the database, thus never making the attachedEntity variable null. msdn.microsoft.com/en-us/library/jj592872(v=vs.113).aspx