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


免責聲明!

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



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