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

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          /// <summary>
     2         /// 监测Context中的Entity是否存在,如果存在,将其Detach,防止出现问题
     3         /// </summary>
     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, out foundEntity);
    13             if (exists)
    14             {
    15                 objContext.Detach(foundEntity);
    16             }
    17             return (exists);
    18         }    
     1         public virtual int Modify(T model, 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循环 被修改的属性名 数组
     9             foreach (string proName in proNames)
    10             {
    11                 //4.4将每个 被修改的属性的状态 设置为已修改状态;后面生成update语句时,就只为已修改的属性 更新
    12                 entry.Property(proName).IsModified = true;
    13             }
    14             //生成sql语句到数据库执行
    15             return db.SaveChanges();
    16         }

     

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值