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的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...
随机推荐
- winedt设置自动显示行号[latex]
options--preferences--appearance 在show line numbers for modes下面的文本框里添加;Tex 这样新建或者打开tex文件的时候就自动显示行号了( ...
- nginx 常用配置说明
一.location 配置 1.1 语法规则: location [=|~|~*|^~] /uri/ { … }= 开头表示精确匹配^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可 ...
- Spring中加载配置文件的方式
原文:http://blog.csdn.net/snowjlz/article/details/8158560 Spring 中加载XML配置文件的方式,好像有3种, XML是最常见的Spring 应 ...
- nodeJS 菜鸟入门
从一个简单的 HTTP 服务开始旅程-- 创建一个 server.js 文件,写入: //最简单的 http 服务例子 var http = require("http"); ht ...
- Direct3D11学习:(五)演示程序框架
转载请注明出处:http://www.cnblogs.com/Ray1024 一.概述 在此系列最开始的文章Direct3D11学习:(一)开发环境配置中,我们运行了一个例子BoxDemo,看过这个例 ...
- Android SQLite的ORM接口实现(一)---findAll和find的实现
最近在看Android的ORM数据库框架LitePal,就想到可以利用原生的SQLite来实现和LitePal类似的ORM接口实现. LitePal有一个接口是这样的: List<Status& ...
- Python装饰器由浅入深
装饰器的功能在很多语言中都有,名字也不尽相同,其实它体现的是一种设计模式,强调的是开放封闭原则,更多的用于后期功能升级而不是编写新的代码.装饰器不光能装饰函数,也能装饰其他的对象,比如类,但通常,我们 ...
- css3照片墙+曲线阴影
css3照片墙+曲线阴影 最近在学习jquery,晚上想复习下以前学过的知识,看到网上有关于css3照片墙的,感觉挺好玩的,就做了做.(以下图片均来自网络) 一.css3照片墙 html部分: < ...
- asp.net url重写相关技术问题整理
1.IIS7配置URL重写需要注意系统是32位还是64位的 在IIS7配置URL重写的时候,需要添加“脚本映射”,如果是64位系统,会有两个地方存放.net framework分别是32位系统和64位 ...
- sprint3(第八天)
昨天忘了发博客,最近在整合前台和后台的内容,在sprint结束前应该能整合好,然后实现前后台的联系,实现点餐功能. 最近要准备大作业也要复习四六级考试,所以花在项目的时间比较少了,请老师谅解. 燃尽图