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

StackOverflow https://stackoverflow.com/questions/12289180

Question

I am trying to find out what is causing this error, I have listed some of the relevant areas of my code that should hopefully help answer my problem.

The recipe entity's members collection is as shown below:

public virtual IList<Member> Members { get; set; }

and here is the Recipes collection on the member entity:

public virtual IList<Recipe> Recipes { get; set; }

I do the below when creating my DbContext in order to make a many-to-many relationship in a separate table

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // have to specify these mappings using the EF Fluent API otherwise I end up with
        // the foreign key fields being placed inside the Recipe and Member tables, which wouldn't
        // give a many-to-many relationship
        modelBuilder.Entity<Recipe>()
            .HasMany(r => r.Members)
            .WithMany(m => m.Recipes)
        .Map(x => {
            x.ToTable("Cookbooks"); // using a mapping table for a many-to-many relationship
            x.MapLeftKey("RecipeId");
            x.MapRightKey("MemberId");
        });

        modelBuilder.Entity<Recipe>()
            .HasRequired(x => x.Author)
            .WithMany()
            .WillCascadeOnDelete(false);

    }

I also seed my database when the model changes and all I have had to do is add to a recipe's member collection and it seems to be able to sort the rest out for me and place the relevant keys in my cookbook relationship table.

This is some of the code in my recipe controller action that performs the work:

var memberEntity = memberRepository.Find((int)memberId);
var recipeEntity = recipeRepository.Find(recipeId);
recipeEntity.Members.Add(memberEntity);
recipeRepository.InsertOrUpdate(recipeEntity);
recipeRepository.Save();

Here is the insert or update method on my Recipe repository

    public void InsertOrUpdate(Recipe recipe)
    {
        if (recipe.Id == default(int))
        {
            // New entity
            context.Recipes.Add(recipe);
        } else
        {
            // Existing entity
            context.Entry(recipe).State = EntityState.Modified;
        }
    }

I get an error of "InvalidOperationException : The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects." on this line:

context.Entry(recipe).State = EntityState.Modified;

Does anyone know why that would happen? Do I have to add the member to the recipe and vice versa to get this to work? I'm not sure what the problem is because the recipeEntity seems to be the correct one.

Any help would be appreciated, thanks.

EDIT The context is being created in each repository (RecipeRepository & MemberRepository) as shown, so I presume this is the problem in that a different context is being used for each .Find() request? and that causes problems?

private EatRateShareDbContext context = new EatRateShareDbContext();
Was it helpful?

Solution

I'm not sure this is the solution but it seems like you're using different contexts in your repository.
First make sure your have the same context for each lifetime. lifetime could be different based on your project type. (e.g. for web projects, usually it is the same for each HttpContext). You can use IoC to manage your context lifetime. Good IoC libraries for .Net are autofac and Castle Windsor

Also, I think your call to InsertOrUpdate method is unnecessary (unless you're calling Find method with no tracking.) just remove the line and see if it works:

var recipeEntity = recipeRepository.Find(recipeId);
recipeEntity.Members.Add(memberEntity);
recipeRepository.Save();

One easy way to share your DbContext per HttpRequest is mentioned here.

OTHER TIPS

If you are using AutoFac, you must add SingleInstance() to your register code.

Example: builder.Register(a => new EntityContainer()).As().SingleInstance()

Where EntityContainer is your DbContext

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