Error multiple objects with the same key DbContext

被刻印的时光 ゝ 提交于 2019-12-02 17:40:21

问题


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?


回答1:


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

}



来源:https://stackoverflow.com/questions/17544705/error-multiple-objects-with-the-same-key-dbcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!