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 ...
随机推荐
- Angularjs学习---官方phonecat实例学习angularjs step0 step1
接下来一系列的文章都是学习https://docs.angularjs.org/tutorial的笔记,主要学习的angular-phonecat项目的实现,来介绍angularjs的使用. 1.下载 ...
- Atitit.创业之uke团队规划策划 v9
Atitit.创业之uke团队规划策划 v9 Uke org prjAuthor撰写人:绰号:老哇的爪子( 全名::Attilax Akbar Al Rapanui 阿提拉克斯 阿克巴 阿尔 拉帕努 ...
- error LNK2038: 检测到“RuntimeLibrary”的不匹配项: 值“MDd_DynamicDebug”不匹配值“MTd_StaticDebug”
今日VS2012 C++编译出现一堆错误: > 正在生成代码... >Code.obj : error LNK2005: "public: __thiscall std::_Co ...
- CSS之flex布局
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...
- Neutron 功能概述 - 每天5分钟玩转 OpenStack(65)
从今天开始,我们将学习 OpenStack 的 Networking Service,Neutron.Neutron 的难度会比前面所有模块都大一些,内容也多一些.为了帮助大家更好的掌握 Neutor ...
- Objective-C中的Block回调模式
在前面的博客中提到了Block的概念和使用方法,个人感觉Block最爽的用法莫过于在回调时用block.感觉比委托回调和目标方法回调用着要顺手,好不好用还得读者亲自用一下才知道.如果 读者之前用过SS ...
- Android随笔之——闹钟制作铺垫之AlarmManager详解
说实话,之前写的两篇博客Android广播机制Broadcast详解.Android时间.日期相关类和方法以及现在要写的,都算是为之后要写的闹钟应用做铺垫,有兴趣的话,大家可以去看看前两篇博客. 一. ...
- 帮公司人事MM做了个工资条拆分工具
引言 偶尔一次午饭时人事说加班加到8点多,纯手工复制粘贴Excel的内容,公司大概150多人吧,每次发工资时都需要这样手动处理,将一个Excel拆分成150多个Excel,再把里面的内容粘过去,如此循 ...
- 小白Linux入门 三
环境变量 shell 变量: 内存空间 ,命名的内存空间 echo $SHELL 其中SHELL是变量 里面是/bin/bash sudo su 进入root printenv 命令 命令: 内部命 ...
- 关于从JSP页面插入数据到数据库中乱码问题的解决
问题描述:最近我在写一个j2ee的留言板系统模块,遇到了一个非常让我头大的问题,当我从JSP页面输入数据后,通过hibernate中的业务逻辑类HQL语句把这个数据插入到本地的mysql数据库中,可是 ...
