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的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...
随机推荐
- wireshark解密本地https流量笔记
此方式支持firefox,chrome 建立path变量 SSLKEYLOGFILE=c:\ssl.key 重启firefox chrome,访问https网站会自动生成ssl session key ...
- python 字符串替换
字符串替换可以用内置的方法和正则表达式完成.1用字符串本身的replace方法: a = 'hello word'b = a.replace('word','python')print b 2用正则表 ...
- [原]Android打包之Gradle打包
最近尝试了一下Android的Gradle打包,发现确实比Ant打包会方便很多,特此记录下来. 注:android的gradle现在插件的版本已经是0.14.3了,对于一些老的方法和api,有一些已经 ...
- Linux SSH 连接不上
http://blog.csdn.net/cryhelyxx/article/details/46473783 在xshell下用ssh登录远程主机centos出现以下问题: Connection e ...
- Eclipse卸载插件
Eclipse卸载插件 ### 本人Eclipse版本为:Eclipse Mars 1. 选择: Help -> Install New Software , 如下图:2. 点击 what is ...
- MyBatis知多少(5)业务对象模型
几乎所有结构良好的软件都使用了分层设计.分层设计将一个应用程序根据技术职能分为几 个内聚的部分,从而将某种特定技术或接口的实现细节与其他部分分离开来.分层设计可以用任 何一种强壮的编程语言来实现.图1 ...
- 再次讲解js中的回收机制是怎么一回事。
在前几天的一篇闭包文章中我们简单的介绍了一下闭包,但是并没有深入的讲解,因为闭包涉及的知识点比较多,为了能够更好的理解闭包,今天讲解一下关于js中的回收机制. 在初识闭包一文中我说过js中有回收机制这 ...
- java正则表达式小练习(IP地址检测、排序,叠词的处理,邮件地址的获取)
import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; import java.util.reg ...
- Java -- 根据当前日期获取当前一周的所有日期
Learn From:http://my.oschina.net/hermer/blog/151274 /** * 测试 * @param args */ public static void mai ...
- [Math] Beating the binary search algorithm – interpolation search, galloping search
From: http://blog.jobbole.com/73517/ 二分检索是查找有序数组最简单然而最有效的算法之一.现在的问题是,更复杂的算法能不能做的更好?我们先看一下其他方法. 有些情况下 ...