Attaching an entity of type 'xxx' failed because another entity of the same type already has

Posted gonghui2016

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Attaching an entity of type 'xxx' failed because another entity of the same type already has相关的知识,希望对你有一定的参考价值。

问题的详细描述:

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;
}

 

以上是关于Attaching an entity of type 'xxx' failed because another entity of the same type already has的主要内容,如果未能解决你的问题,请参考以下文章

General structure of QKDN

hibernate4多对多Use of @OneToMany or @ManyToMany targeting an unmapped class:

JPA:identifier of an instance of was altered from

An entity cannot be annotated with both @Entity and @MappedSuperclass: com.example1.demo1.Entity.Use

什么是modelBuilder.entity(Of x)

@ManyToOne references an unknown entity: