Entity Framework: "The relationship between two objects cannot be determined because they are bound to different ObjectContext objects."

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 (in the line "project.ProjectUsers.Add (ProjectUser)")

"The relationship between two objects cannot be determined because they are bound to different ObjectContext objects."

I don’t understand why the reason, as far as I know, both objects use the same ObjectContext (but I am new to EF).

What am I doing wrong? Thank you for your help!

+5
source share
5 answers

user , .

, Project ProjectUser, , ProjectUser - , , Project, .

, , .

+7

Project, ProjectUser . :

context.AddObject(project);

context.AddObject(projectUser);

, .

+4

:

project.ProjectUsers.Add(projectUser);

, .

context.AddObject(project);
0

, - application database singleton. :

ApplicationDbContext.cs `Java

public class ApplicationDbContext : DbContext, IDbContextFactory<DbContext>
{
    protected static ApplicationDbContext _instance { private set; get; }

    private ApplicationDbContext() : base("ApplicationDbContext")
    {
    }

    public DbContext Create()
    {
        return getInstance();
    }


    public static ApplicationDbContext getInstance()
    {
        if (_instance == null) {
            _instance = new ApplicationDbContext();
        }
        return _instance;
    }
}

`

`Java

private ApplicationDbContext _db;

public class HelloController : Controller
{
    _db = ApplicationDbContext.getInstance();
}

`

, ,

0

, , , , , , , .

With Ninject control dependencies, I needed to specify

kernel.Bind<Context>().ToSelf().InSingletonScope();

before my EF calls between UserManager and various controllers start behaving correctly.

0
source

All Articles