Question

I have recently changed from ObjectContext to DbContext using EntityFramwework by upgrading to EF6

Most stuff works, but saving and updating won't. Here is an example:

public void AssignToAdmin(Product product, Admin admin)
{
    var pcsps = from s in context.ProductCreationSections
                join pcsp in context.ProductCreationSectionAndProducts on s.ProductCreationSecitionID equals pcsp.ProductCreationSectionID
                where pcsp.ProductID == product.ProductID && s.IsManagerAssigned
                select pcsp;

    foreach (var pcsp in pcsps.Include("AssignedAdmins"))
    {
        pcsp.AssignedAdmins.Add(admin);
    }
}

Trying to execute the line pcsp.AssignedAdmins.Add(admin), I get the error:

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

There is one context for the class and it comes from Dependency Injection (the class is a Service in an MVC app).

I've tried removing/attaching and so on, but this doesn't fix it - it just gives different error messages. It's not even obvious which entity is using another context.

Any ideas of where this other context the error message refers to is coming from?

Was it helpful?

Solution 2

Sorted it, but it was quite a major refactor.

The issue was that each service received it's own instance of 'context', so when two entities from two services were expected to work together, they wouldn't as each belonged to a different context.

One solution would have been to make the class that created the context a 'Singleton' so that it always returned the same instance, but that would have been very BAD as every page would then use the same context.

Each service got it's own instance of 'context' through Dependency Injection. I changed the project so only the controllers got an instance of context through DI. Then, in the controller constructor, this context was passed to the services that the controller had received through dependency injection.

This way, each request only ever uses a single instance of context, but this instance is still short lived, as it is supposed to be as each request has its own context and doesn't share one.

Not sure this is the way it is supposed to work, but given the web app I was working with, this seemed to be the best solution.

I also had to go through and add a 'context.SaveChanges();' statement everywhere a change to the database was made.

Not sure why this should be when the old version of EF did this automatically, but it now works.

Thanks for the advice Derrick

OTHER TIPS

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

Where has admin come from? Getting the admin object from the same context as the pcsp object should help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top