Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8480021
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T19:11:36+00:00 2026-06-10T19:11:36+00:00

I am trying to find out what is causing this error, I have listed

  • 0

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();
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T19:11:36+00:00Added an answer on June 10, 2026 at 7:11 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am just trying to find out that does puppet have something similar to
I trying to find out the visibility of the Excel and do some activities
I am trying to find out how to write an SQL statement that will
I'm trying to find out some matrix multiplication/inversion benchmarks online. My C++ implementation can
Trying to find out if it's possible to use SQLAlchemy on Heroku. Thanks.
i m trying to find out how to convert timestamp date and time (
I am trying to find out a way to set a time tag to
I am trying to find out if an instance of an application (not vb.net)
I'm trying to find out how to change the icon of a JStree node
I'm trying to find out a little bit more about how the preprocessor works

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.