Search code examples
c#dbcontextupdating

Error multiple objects with the same key DbContext


I am getting an Error

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

I used this method in two places. In first place - work correctly, but in second I have error.

How decided this problem?

My method:

public static void UpdateMehod(ModelEntities context, ProcessedFilest processedFiles)
{
    context.Set<ProcessedFiles>().Attach(processedFiles);
    context.Entry(processedFiles).Property(p => p.ID).IsModified = true;
    context.SaveChanges();
}

I create new method:

public static void UpdateProtocol(ModelEntities context, ProcessedFilesXml processedFilesXml) { var entry = context.Entry(processedFilesXml);

        if (entry.State == EntityState.Detached)
        {
            var set = context.Set<ProcessedFilesXml>();
            ProcessedFilesXml attachedEntity = set.Find(processedFilesXml.ProcessedFileXmlID); 

            if (attachedEntity != null)
            {
                var attachedEntry = context.Entry(attachedEntity);
                attachedEntry.CurrentValues.SetValues(processedFilesXml);
            }
            else
            {
                entry.State = EntityState.Modified; 
            }
        }

        //context.Set<ProcessedFilesXml>().Attach(processedFilesXml);
        //context.Entry(processedFilesXml).Property(p => p.Protocol).IsModified = true;
        //context.SaveChanges();
    }

But I don't know ho create savechanges?


Solution

  • If you load the entity from the context you cannot attach an entity with the same key agai.See this question or this

    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.Find(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
            }
        }
    enter code here
    

    }