An entity object cannot be referenced by multiple instances of IEntityChangeTracker 的解决方案
使用EF对建立了关系的表新增记录时出现:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker 或一个实体对象不能由多个 IEntityChangeTracker 实例引用
在学习MVC+EF做demo时碰到的一个异常信息。在网上查了些,看得不是很明白,就自己折腾了一会儿。
先上出错的代码:
public class CollegeInfo
{
private StudentManageContext stuCtx=new StudentManageContext();
public Models.CollegeInfoModel GetModel(Guid collegeId)
{
var model = stuCtx.CollegeInfoes.SingleOrDefault(s => s.CollegeId == collegeId); return model;
} public int Add(Models.CollegeInfoModel model)
{
stuCtx.CollegeInfoes.Add(model);
int count = stuCtx.SaveChanges();
return count;
} public int Update(Models.CollegeInfoModel model)
{
Models.CollegeInfoModel oldModel = stuCtx.CollegeInfoes.Find(model.CollegeId);
oldModel = model;
stuCtx.Entry(oldModel).State = System.Data.EntityState.Modified;
return stuCtx.SaveChanges();
}
}
public class DepartmentInfo
{
private StudentManageContext stuCtx=new StudentManageContext();
public Models.DepartmentInfoModel GetModel(Guid departmentId)
{
var model = stuCtx.DepartmentInfoes.SingleOrDefault(s => s.DepartmentId == departmentId); return model;
} public int Add(Models.DepartmentInfoModel model)
{
stuCtx.DepartmentInfoes.Add(model);
int count = stuCtx.SaveChanges(); return count;
} public int Update(Models.DepartmentInfoModel model)
{
Models.DepartmentInfoModel oldModel = stuCtx.DepartmentInfoes.Find(model.DepartmentId);
oldModel = model;
stuCtx.Entry(oldModel).State = System.Data.EntityState.Modified;
return stuCtx.SaveChanges();
}
}
使用表关系图:
两个表是一对多的关系。DepartmentInfo 中的collegeInfoId是外键。
添加DepartmentInfo代码:
static void Main(string[] args)
{
Database.SetInitializer<StudentManageContext>(new DropCreateDatabaseIfModelChanges<StudentManageContext>());
CollegeInfoModel collegex = new BLL.CollegeInfo().GetModel(new Guid("B956CA6F-DD7D-4436-9099-484366A5F0B7"));
DepartmentInfoModel depart = new DepartmentInfoModel()
{
DepartmentId = Guid.NewGuid(),
DepartmentName = "depart" + DateTime.Now.ToString(),
CollegeInfoObj = collegex
};
new BLL.DepartmentInfo().Add(depart);
}
这时会出现An entity object cannot be referenced by multiple instances of IEntityChangeTracker 或一个实体对象不能由多个 IEntityChangeTracker 实例引用的异常
原因是 CollegeInfoModel collegex = new BLL.CollegeInfo().GetModel(new Guid("B956CA6F-DD7D-4436-9099-484366A5F0B7")); 和 new BLL.DepartmentInfo().Add(depart); 这两句代码使用的是两个不同的StudentManageContext 对象造成的,可以仔细看看出错代码,两个类都有 private StudentManageContext stuCtx=new StudentManageContext(); ,到这儿你是否明白了呢。简单的来说,你要做的操作都必须在同一DbContext上完成。注:StudentManageContext派生于DbContext.
解决方案一:
static void Main(string[] args)
{
Database.SetInitializer<StudentManageContext>(new DropCreateDatabaseIfModelChanges<StudentManageContext>()); CollegeInfoModel collegex = new BLL.CollegeInfo().GetModel(new Guid("B956CA6F-DD7D-4436-9099-484366A5F0B7")); DepartmentInfoModel depart = new DepartmentInfoModel()
{
DepartmentId = Guid.NewGuid(),
DepartmentName = "depart" + DateTime.Now.ToString(), };
//new BLL.DepartmentInfo().Add(depart); 将这句代码改成下面两句
collegex.Departments.Add(depart);
new BLL.CollegeInfo().Update(collegex);
}
原因就是:Update时与GetModel用得时同一个DBContext。
解决方案二:
public class CollegeInfo:BaseModel
{
public Models.CollegeInfoModel GetModel(Guid collegeId)
{
var model = stuCtx.CollegeInfoes.SingleOrDefault(s => s.CollegeId == collegeId); return model;
} public int Add(Models.CollegeInfoModel model)
{
stuCtx.CollegeInfoes.Add(model);
int count = stuCtx.SaveChanges();
return count;
} public int Update(Models.CollegeInfoModel model)
{
Models.CollegeInfoModel oldModel = stuCtx.CollegeInfoes.Find(model.CollegeId);
oldModel = model;
stuCtx.Entry(oldModel).State = System.Data.EntityState.Modified;
return stuCtx.SaveChanges();
}
}
public class DepartmentInfo:BaseModel
{ public Models.DepartmentInfoModel GetModel(Guid departmentId)
{
var model = stuCtx.DepartmentInfoes.SingleOrDefault(s => s.DepartmentId == departmentId); return model;
} public int Add(Models.DepartmentInfoModel model)
{
stuCtx.DepartmentInfoes.Add(model);
int count = stuCtx.SaveChanges(); return count;
} public int Update(Models.DepartmentInfoModel model)
{
Models.DepartmentInfoModel oldModel = stuCtx.DepartmentInfoes.Find(model.DepartmentId);
oldModel = model;
stuCtx.Entry(oldModel).State = System.Data.EntityState.Modified;
return stuCtx.SaveChanges();
}
}
public abstract class BaseModel
{
protected StudentManageContext stuCtx = null;
public BaseModel()
{
stuCtx = DataCache.GetCache("StudentManageContext") as StudentManageContext;
if (stuCtx == null)
{
stuCtx = new StudentManageContext();
DataCache.SetCache("StudentManageContext", stuCtx);
}
}
}
这样的话可以让CollegeInfo和DepartmentInfo共用同一个DBContext。
An entity object cannot be referenced by multiple instances of IEntityChangeTracker 的解决方案的更多相关文章
- EntityFramework 异常 -- An entity object cannot be referenced by multiple instances of IEntityChangeTracker
问题 在调用 DbSet 的 Attach() 方法时(与将 Entity 设置为 EntityState.Unchanged 状态等价)报告以下错误: An entity ob ...
- EF异常探究(An entity object cannot be referenced by multiple instances of IEntityChangeTracker.)
今天在改造以前旧项目时出现了一项BUG,是由于以前不规范的EF写法所导致.异常信息如下: "An entity object cannot be referenced by multiple ...
- An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
如果你和我一样遇到了这个问题,那么你就要检查你要操作的Model对象查询,更新操作的数据库上下文也就是DBContext是否一致.如果不一致也就是说你用AContext去查如AContext.SET& ...
- EBS OAF开发中的Java 实体对象(Entity Object)验证功能补充
EBS OAF开发中的Java 实体对象(Entity Object)验证功能补充 (版权声明,本人原创或者翻译的文章如需转载,如转载用于个人学习,请注明出处:否则请与本人联系,违者必究) EO理论上 ...
- 解决删除镜像时image is referenced in multiple repositories
1.查看镜像 docker images rt@:~# docker images REPOSITORY TAG IMAGE ID CREATED SIZE hours ago MB f8ab12e0 ...
- 【Plink】Error: Multiple instances of '_' in sample ID.?
目录 前言 原因 解决方法 方法一:修改样本名 方法二:修改--id-delim 方法三:加入--double_id或--const-fid参数 前言 将vcf转化为plink格式时,命令如下: pl ...
- docker删除镜像文件时,出现image is referenced in multiple repositories如何解决
1.输入查看镜像文件的命令: $ docker image ls 得到如下结果: 2.删除名为lihui/demo的镜像,输入如下命令: $ docker rmi 9fa504a6066a 报错,报错 ...
- Running multiple instances of Xamarin Studio on a Mac
I love developing software on my MacBook Air! I got the latest version with the maximum possible spe ...
- electron-vue-webpack引入bootstrap多实例问题Multiple instances of Vue detected!
在node modules里面找到electron-webpack目录, 修改out->main.js白名单内容,增加 whiteListedModules.add("bootstra ...
随机推荐
- salesforce 零基础学习(四十八)自定义列表分页之Pagination基类封装 ※※※
我们知道,salesforce中系统标准列表页面提供了相应的分页功能,如果要使用其分页功能,可以访问http://www.cnblogs.com/zero-zyq/p/5343287.html查看相关 ...
- SSISDB1:使用SSISDB管理SSIS Projects
使用Project Deployment Model,将SSIS Project部署到Integration Services Catalog之后,SSISDB负责管理SSIS Project.在SS ...
- SQL Server 堆表行存储大小(Record Size)
一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 堆表行记录存储格式(Heap) 案例分析(Case) 参考文献(References) 二.背 ...
- Myeclipse 安装SVN步骤
非在线安装 首先来这儿下载插件 http://subclipse.tigris.org/servlets/ProjectDocumentList?folderID=2240 找个最新的下载 解压到对应 ...
- 《JS设计模式笔记》 3,观察者模式
<script type="text/javascript"> //挂插着模式又叫发布订阅模式应该是最常用的模式 //1,dom事件就是观察者模式,只要订阅了click ...
- ASP.NET MVC之视图生成URL(二)
前言 上一节我们讲述了MVC中从控制器到视图传递数据的四种方式,想必大家早已掌握了,那我们继续往下走. 话题 在MVC的Web应用程序中,我们经常会出现这样的操作,从一个视图跳转到另外一个视图,大部分 ...
- Hawk 3.1 动态页面,ajax,瀑布流
不少朋友反映,Hawk的手气不错,好像没法处理动态页面.其实很容易,比其他软件都容易,让我慢慢道来. 1. 什么是动态页面 很多网站,在刷新的时候会返回页面的全部内容,但实际上只需要更新一部分,这样可 ...
- 在ASP.NET Web API项目中使用Hangfire实现后台任务处理
当前项目中有这样一个需求:由前端用户的一个操作,需要触发到不同设备的消息推送.由于推送这个具体功能,我们采用了第三方的服务.而这个服务调用有时候可能会有延时,为此,我们希望将消息推送与用户前端操作实现 ...
- 升级 Visual Studio 2015 CTP 5 的坑、坑、坑
前两天,微软发布了 Visual Studio 2015 CTP 5,全称为 Visual Studio 2015 Community Technology Preview 5,意为社区技术预览版,之 ...
- canvas 图片拖拽旋转之二——canvas状态保存(save和restore)
引言 在上一篇日志“canvas 图片拖拽旋转之一”中,对坐标转换有了比较深入的了解,但是仅仅利用坐标转换实现的拖拽旋转,会改变canvas坐标系的状态,从而影响画布上其他元素的绘制.因此,这个时候需 ...
