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.
按字面意思看,发生异常的原因在于已经存在了一个实体与要进行操作的实体存在相同的主键,相互冲突。
解决方案:
- 查询时让EF不要跟踪
即在使用EF上下文对象查询数据时添加 AsNoTracking(),显示声明不要让EF跟踪对象
/// <summary>
/// 根据指定条件查询数据
/// </summary>
/// <param name="whereLambda">查询条件 Linq表达式 </param>
/// <returns>符合条件的数据列表</returns>
public virtual List<T> GetListBy(Expression<Func<T, bool>> whereLambda)
{
return db.Set<T>().Where(whereLambda).AsNoTracking().ToList();
} - 在进行更新和删除时首先移除主键实体(如果存在)再进行操作
首先检查是否已经存在相同主键实体,如果存在则移除,然后再开始进行更新或删除处理,由于新增时,主键一定不会相同,因此新增数据可以不需要判断是否存在相同主键实体。
/// <summary>
/// 监测Context中的Entity是否存在,如果存在,将其Detach,防止出现问题
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
private bool RemoveHoldingEntityInContext(T entity)
{
ObjectContext objContext = ((IObjectContextAdapter)db).ObjectContext;
var objSet = objContext.CreateObjectSet<T>();
var entityKey = objContext.CreateEntityKey(objSet.EntitySet.Name, entity);
object foundEntity;
var exists = objContext.TryGetObjectByKey(entityKey, out foundEntity);
if (exists)
{
objContext.Detach(foundEntity);
}
return (exists);
}public virtual int Modify(T model, params string[] proNames)
{
RemoveHoldingEntityInContext(model);
//4.1将 对象 添加到 EF中
DbEntityEntry entry = db.Entry(model);
//4.2先设置 对象的包装 状态为 Unchanged
entry.State = EntityState.Unchanged;
//4.3循环 被修改的属性名 数组
foreach (string proName in proNames)
{
//4.4将每个 被修改的属性的状态 设置为已修改状态;后面生成update语句时,就只为已修改的属性 更新
entry.Property(proName).IsModified = true;
}
//生成sql语句到数据库执行
return db.SaveChanges();
}
Stackflow上也有一篇文章这样的问题,传送门
博客园上也有一篇,解决方案,传送门
ASP.NET MVC 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.
问题的详细描述: Attaching an entity of type 'xxxxx' failed because another entity of the same type already ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第一章:创建基本的MVC Web站点
在这一章中,我们将学习如何使用基架快速搭建和运行一个简单的Microsoft ASP.NET MVC Web站点.在我们马上投入学习和编码之前,我们首先了解一些有关ASP.NET MVC和Entity ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之目录导航
ASP.NET MVC with Entity Framework and CSS是2016年出版的一本比较新的.关于ASP.NET MVC.EF以及CSS技术的图书,我将尝试着翻译本书以供日后查阅. ...
- 使用MiniProfiler给Asp.net MVC和Entity Framework号脉(附源码)
在学习python开发框架pylons/pyramid的过程中,里面有个非常棒的页面性能监控功能,这样在开发过程中,你能清楚的知道当前页面的性能以及其它参数. 这里介绍一下如何给Asp.net MVC ...
- ASP.NET MVC+EasyUI+Entity FrameWork 整合开发
本文详细讲解怎么用ASP.NET MVC+EasyUI+Entity FrameWork 来开发一个项目 对于ASP.NET MVC的Jscript库,主要引用 <script type=.mi ...
- Using the Repository Pattern with ASP.NET MVC and Entity Framework
原文:http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-and ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第六章:管理产品图片——多对多关系(上篇)
在这章中,我们将学习如何创建一个管理图片的新实体,如何使用HTML表单上传图片文件,并使用多对多关系将它们和产品关联起来,如何将图片存储在文件系统中.在这章中,我们还会学习更加复杂的异常处理,如何向模 ...
- [转]Using the Repository Pattern with ASP.NET MVC and Entity Framework
本文转自:http://www.codeguru.com/csharp/.net/net_asp/mvc/using-the-repository-pattern-with-asp.net-mvc-a ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库
在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...
随机推荐
- iis错误记录
1:iis错误 解决方法: 输入C:\Windows\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis -i 这里由于我的是默认在Administ ...
- LDPC编译码基本原理
LDPC编译码基本原理 学习笔记 V1.1 2015/02/18 LDPC编译码基本原理 概述 本文是个人针对LDPC的学习笔记,主要针对LDPC译码算法做了简要的总结.该版本主要致力 ...
- C#将Json字符串反序列化成List对象类集合
摘自:http://blog.csdn.net/cdefg198/article/details/7520398 using System.IO; using System.Web.Script.Se ...
- boi剖析 - 基于webpack的css sprites实现方案
本文是58到家前端工程化集成解决方案boi的博文系列之一.boi是基于webpack打造的一站式前端工程化解决方案,现已开源Github. 作为前端构建工具不可或缺的一个环节,自动生成css spri ...
- Hadoop第4周练习—HDFS读写文件操作
1 运行环境说明... 3 :编译并运行<权威指南>中的例3.2. 3 内容... 3 2.3.1 创建代码目录... 4 2.3.2 建立例子文件上传到hdfs中... 4 ...
- Keypress – 超强大!捕获键盘输入的 JavaScript 库
Keypress 是一个强大的 JavaScript 库,用于捕获键盘输入.这是一个有非常特殊的功能的输入捕获库,它是很容易掌握和使用,并且不依赖第三方库.在网站开发中,经常会碰到需要处理键盘输入的场 ...
- 高级四则运算器—结对项目总结(193 &105)
高级四则运算器—结对项目总结 为了将感想与项目经验体会分割一下,特在此新开一篇博文. 界面设计 啥都不说,先上图震慑一下... 上面的三个界面是我们本次结对项目的主界面,恩,我也觉得挺漂亮的!你问我界 ...
- Res_Orders_01之需求分析
Res_Orders_01之需求分析 一.背景及好处 为了提高餐厅的运营效率,增强餐厅各部门间的配合,减少顾客到店后的点餐.等餐及结算过程消耗的时间,降低服务员点餐失误率,进一步提高餐厅管理人员对菜品 ...
- Github教程(3)
Pull Request Pull Request 是自己修改源代码后,请求对方仓库采纳该修改时采取的一种行为. 场景1: 用户A在fork完用户B的项目时,A修改了代码并提交了一个Pull Requ ...
- ADO.NET 基础
*程序要和数据库交互要通过ADO.NET进行,通过ADO.NET就能在程序中执行SQL了,ADO.NET中提供了对各种不同数据库的统一操作接口. 1.连接SQLServer 连接字符串,程序通过链接字 ...