实体框架:“由于两个对象之间的关系被附加到不同的ObjectContext对象,因此无法定义." [英] Entity Framework: "The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects."

查看:32
本文介绍了实体框架:“由于两个对象之间的关系被附加到不同的ObjectContext对象,因此无法定义."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码(带有EF 4的VS2010 ASP.NET MVC 3):

I have this code (VS2010 ASP.NET MVC 3 with EF 4):

Project project = new Project();
project.Number = number;
project.Name = name;
context.AddObject(project);

ProjectUser projectUser = new ProjectUser();
projectUser.User = user;
projectUser.Status = 1;
project.ProjectUsers.Add(projectUser);

context.SaveChanges(true);

它会产生以下错误(在"project.ProjectUsers.Add(projectUser)"行上)

It generates the following error (on the "project.ProjectUsers.Add(projectUser)" line)

由于两个对象被附加到不同的ObjectContext对象,因此无法定义它们之间的关系."

"The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects."

据我所知,我不明白为什么会导致两个对象都使用相同的ObjectContext(但我是EF的新手).

I don't understand why cause, as far as I know, both objects are using the same ObjectContext (but I'm new to EF).

我做错了什么?感谢您的帮助!

What am I doing wrong? Thanks for your help!

推荐答案

如果您的 user 变量是实体类型,并且已分配给其他上下文,则您会遇到此问题.

If your user variable is an entity type, and it is assigned to a different context, then you'd experience this problem.

我不认为问题出在您的 Project ProjectUser 对象之间,只是因为您的 ProjectUser 对象未明确分配给上下文-我认为默认情况下,保存时它将与 Project 进入相同的上下文.

I don't think the problem is between your Project and ProjectUser objects, only because your ProjectUser object isn't explicitly assigned to a context - I think by default it will go to the same context as the Project when you go to save it.

我相信只有当您真正拥有两个上下文并尝试将它们结合在一起时,您才会遇到此错误.

I believe you get this error only when you truly have two contexts and try to join them together.

这篇关于实体框架:“由于两个对象之间的关系被附加到不同的ObjectContext对象,因此无法定义."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆