zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    lvs三种模式的优缺点对比
    linux下的$0-n作用
    图解 HTTP 笔记(一)——了解 Web 及网络基础
    从源码学习使用 node-delegates
    从源码看 Vue 中的 Mixin
    常见 Web 性能优化方式
    解密虚拟 DOM——snabbdom 核心源码解读
    浅谈 JSONP
    代码覆盖率测试及 GitHub 自动化集成
    Redis 学习笔记
  • 原文地址:https://www.cnblogs.com/gonghui2016/p/11957018.html
Copyright © 2011-2022 走看看