Attaching an entity of type 'xxx' failed because another entity of the same type already has the same primary key value.


問題的詳細描述:

Attaching an entity of type 'xxxxx' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

解決方案:

public void Update(T entity)
{
    if (entity == null)
    {
        throw new ArgumentException("entity");
    }
    if (this.Entry(entity).State == EntityState.Detached)
    {
        HandleDetached(entity);
    }
    this.Table.Attach(entity);
    this.Entry(entity).State = EntityState.Modified;
    this.SaveChanges();
}

private bool HandleDetached(T entity)
{
    var objectContext = ((IObjectContextAdapter)this).ObjectContext;
    var entitySet = objectContext.CreateObjectSet<T>();
    var entityKey = objectContext.CreateEntityKey(entitySet.EntitySet.Name, entity);
    object foundSet;
    bool exists = objectContext.TryGetObjectByKey(entityKey, out foundSet);
    if (exists)
    {
        objectContext.Detach(foundSet);
    }
    return exists;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM