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 ...
随机推荐
- KnockoutJS 3.X API 第六章 组件(2) 组件注册
要使Knockout能够加载和实例化组件,必须使用ko.components.register注册它们,从而提供如此处所述的配置. 注意:作为替代,可以实现一个自定义组件加载器(自定义加载器下一节介绍 ...
- li 前面的缩进怎么去除?
异常处理汇总-前端系列 http://www.cnblogs.com/dunitian/p/4523015.html 设置margin和padding为0或者为比较小的值就可以了
- jQuery2.0.3源码分析系列(28) 元素大小
最近的分析都是有点不温不火,基本都是基础的回顾了 今年博客的目标目前总的来说有2大块 JS版的设计模式,会用jQuery来诠释 JS版的数据结构,最近也一直在狠狠的学习中. HTML息息相关的的样式 ...
- Android探索之Service全面回顾及总结
什么是Service? Service(服务)是Android提供的四大组件之一,是一个没有用户界面的在后台运行执行耗时操作的应用组件.其他应用组件能够启动Service,并且当用户切换到另外的应用场 ...
- MySQL学习笔记八:日期/时间的处理
MySQL日期时间的处理,在其官网文档上都有详细的阐述,想了解更多的同学可自行查阅. 1.查询当前日期时间:函数有now(),localtime(),current_timestamp(),sysda ...
- [ROS] Studying Guidance
Reference: https://www.zhihu.com/question/35788789 安装指南:http://wiki.ros.org/indigo/Installation/Ubun ...
- Linux分区:超过2TB硬盘分区
测试iscsi服务是否正常 [root@FocusBackup ~]# service iscsi restart 停止 iscsi: ...
- Kooboo CMS 之TextContent详解
TextCotent 在Kooboo.CMS.Content下面,在View中有使用到这个模型层. TextContent继承了ContentBase,而ContentBase是由2个部分类组成的,一 ...
- Windows Server 2008 下解析二级域名的方法
昨天去了客户那里部署网站,用的是客户那边的windows server 2008. 本文主要以总结问题点的形式来说. 问题1:本机的数据库是SQL SERVER 2008R2,客户那边的数据库是SQL ...
- H5基于iScroll实现下拉刷新,上拉加载更多
前言 前一段有个手机端的项目需要用到下拉刷新和上拉加载更多的效果,脑海里第一反映就是微博那种效果,刚开始的理解有些偏差,以为下拉也是追加数据,上拉也是追加数据,后请教同事后发现其实下拉只是刷新最新数据 ...
