"The connection between the two objects cannot be specified since they are tied to distinct ObjectContext objects," according to Entity Framework.

c# entity-framework

Question

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);

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

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

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!

1
5
7/14/2011 9:06:56 PM

Accepted Answer

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

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.

7
7/14/2011 9:24:23 PM

Popular Answer

Just list you did for Project, you need to add the ProjectUser to the context. So mimic the line:

context.AddObject(project);

And instead make it

context.AddObject(projectUser);

And do that before you add it to the collection on project.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow