加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

ASP.NET MVC another entity of the same type already has the

发布时间:2020-12-16 08:59:34 所属栏目:asp.Net 来源:网络整理
导读:ASP.NET MVC项目?Repository层中,Update、Delete总是失败 another entity of the same type already has the same primary key value 在项目里的Repository层中的涉及到数据的update方法总是报错,delete时有时也会报错,报的错误是 Attaching an entity of

ASP.NET MVC项目?Repository层中,Update、Delete总是失败

another entity of the same type already has the same primary key value

在项目里的Repository层中的涉及到数据的update方法总是报错,delete时有时也会报错,报的错误是

Attaching an entity of type 'Model.Diary' 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.

?

按字面意思看,发生异常的原因在于已经存在了一个实体与要进行操作的实体存在相同的主键,相互冲突。

解决方案:

  1. 查询时让EF不要跟踪

    即在使用EF上下文对象查询数据时添加 AsNoTracking(),显示声明不要让EF跟踪对象

    ?

    1         /// <summary>
    2         /// 根据指定条件查询数据
    3         </summary>
    4         <param name="whereLambda">查询条件 Linq表达式    </param>
    5         <returns>符合条件的数据列表</returns>
    6         public virtual List<T> GetListBy(Expression<Func<T,bool>> whereLambda)
    7         {
    8             return db.Set<T>().Where(whereLambda).AsNoTracking().ToList();
    9         }    

    ?

  2. 在进行更新和删除时首先移除主键实体(如果存在)再进行操作

    首先检查是否已经存在相同主键实体,如果存在则移除,然后再开始进行更新或删除处理,由于新增时,主键一定不会相同,因此新增数据可以不需要判断是否存在相同主键实体。

    ?

     1           2          监测Context中的Entity是否存在,如果存在,将其Detach,防止出现问题
     3          4         <param name="entity"></param>
     5         <returns></returns>
     6         private bool RemoveHoldingEntityInContext(T entity)
     7  8             ObjectContext objContext = ((IObjectContextAdapter)db).ObjectContext;
     9             var objSet = objContext.CreateObjectSet<T>();
    10             var entityKey = objContext.CreateEntityKey(objSet.EntitySet.Name,entity);
    11             object foundEntity;
    12             var exists = objContext.TryGetObjectByKey(entityKey,1)">out foundEntity);
    13             if (exists)
    14             {
    15                 objContext.Detach(foundEntity);
    16             }
    17             return (exists);
    18         }    
     1         virtual int Modify(T model,1)">params string[] proNames)
     2  3             RemoveHoldingEntityInContext(model);
     4             //4.1将 对象 添加到 EF中
     5             DbEntityEntry entry = db.Entry(model);
     6             4.2先设置 对象的包装 状态为 Unchanged
     7             entry.State = EntityState.Unchanged;
     8             4.3循环 被修改的属性名 数组
    foreach (string proName in proNames)
    10 11                 4.4将每个 被修改的属性的状态 设置为已修改状态;后面生成update语句时,就只为已修改的属性 更新
    12                 entry.Property(proName).IsModified = true;
    13 14             生成sql语句到数据库执行
    15              db.SaveChanges();
    16         }

    ?

Stackflow上也有一篇文章这样的问题,传送门

博客园上也有一篇,解决方案,传送门

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读