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 'xxx' 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 bool Update(T Entity)
            {
                T _local = _DbContextHandle.Set<T>().Local.FirstOrDefault(a => a.id == Entity.id);
                if (_local == null)
                {
                    _DbContextHandle.Set<T>().Attach(Entity);
                    _DbContextHandle.Entry<T>(Entity).State = EntityState.Modified;
                }
                else
                {
                    _DbContextHandle.Entry(_local).CurrentValues.SetValues(Entity);
                    _DbContextHandle.Entry(_local).State = EntityState.Modified;
                }
                return _DbContextHandle.SaveChanges() > 0;
                //以下代码可用#####
                //T t = _DbContextHandle.Set<T>().Local.FirstOrDefault(a => a.id == Entity.id);
                //if (t != null)
                //{//手动删除已存在的实体
                //    //_DbContextHandle.Set<T>().Attach(Entity);
                //    _DbContextHandle.Entry<T>(t).State = EntityState.Detached;
                //}
                //_DbContextHandle.Set<T>().Attach(Entity);
                //var aaa = _DbContextHandle.Entry<T>(Entity);
                //aaa.State = EntityState.Modified;
                //return _DbContextHandle.SaveChanges() > 0;
            }

  • 相关阅读:
    聊聊、Highcharts 动态数据
    聊聊、Zookeeper Linux 启动
    聊聊、Zookeeper 客户端 Curator
    聊聊、Zookeeper 客户端 ZkClient
    聊聊、Zookeeper API
    聊聊、Zookeeper 数据结构和操作命令
    聊聊、Java 网络编程
    《Mysql 索引
    《Mysql 事务
    《Mysql 一条 SQL 更新语句是如何执行的?(Redo log)》
  • 原文地址:https://www.cnblogs.com/pzxnet/p/12980315.html
Copyright © 2011-2022 走看看