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 784151
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T20:40:01+00:00 2026-05-14T20:40:01+00:00

I have a many-to-many relationship between Issues and Scopes in my EF Context. In

  • 0

I have a many-to-many relationship between Issues and Scopes in my EF Context. In ASP.NET MVC, I bring up an Edit form that allows the user to edit a particular Issue. At the bottom of the form, is a list of checkboxes that allow them to select which scopes apply to this issue. When editing an issue, it likely will always have some Scopes associated with it already–these boxes will be checked already. However, the user has the opportunity to check more scopes or remove some of the currently checked scopes. My code looked something like this to save just the Issue:

            using (var edmx = new MayflyEntities())
            {
                Issue issue = new Issue { IssueID = id, TSColumn = formIssue.TSColumn };
                edmx.Issues.Attach(issue);

                UpdateModel(issue);

                if (ModelState.IsValid)
                {
                    //if (edmx.SaveChanges() != 1) throw new Exception("Unknown error. Please try again.");
                    edmx.SaveChanges();
                    TempData["message"] = string.Format("Issue #{0} successfully modified.", id);
                }
            }

So, when I try to add in the logic to save the associated scopes, I tried several things, but ultimately, this is what made the most sense to me:

            using (var edmx = new MayflyEntities())
            {
                Issue issue = new Issue { IssueID = id, TSColumn = formIssue.TSColumn };
                edmx.Issues.Attach(issue);

                UpdateModel(issue);

                foreach (int scopeID in formIssue.ScopeIDs)
                {
                    var thisScope = new Scope { ID = scopeID };
                    edmx.Scopes.Attach(thisScope);
                    thisScope.ProjectID = formIssue.ProjectID;
                    if (issue.Scopes.Contains(thisScope))
                    {
                        issue.Scopes.Attach(thisScope); //the scope already exists
                    }
                    else
                    {
                        issue.Scopes.Add(thisScope); // the scope needs to be added
                    }
                }

                if (ModelState.IsValid)
                {
                    //if (edmx.SaveChanges() != 1) throw new Exception("Unknown error. Please try again.");
                    edmx.SaveChanges();
                    TempData["message"] = string.Format("Issue #{0} successfully modified.", id);
                }
            }

But, unfortunately, that just throws the following exception:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

What am I doing wrong?

  • 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-05-14T20:40:01+00:00Added an answer on May 14, 2026 at 8:40 pm

    Stubs are generally only effective for 1-* relationships.
    *-* relationships introduce a different set of challenges.

    Namely that when you attach both ends – unlike 1-* – you still have no idea if the relationship already exists or not.

    So that means that this code:

    if (issue.Scopes.Contains(thisScope))
    

    Is probably going to return false every time.

    What I would do is this:

    edmx.Issues.Attach(issue);
    UpdateModel(issue);
    // or ctx.LoadProperty(issue, "Scopes") if it is a POCO class.
    issue.Scopes.Load(); // hit the database to load the current state.
    

    Now you need to find out what you need to add & remove from issue.Scopes.
    You can do this by comparing based on ID.

    i.e. if you have a set of Scope IDs you want to have related to the issue (relatedScopes)

    Then this code works out what to add and what to remove.

    int[] toAdd = relatedScopes.Except(issue.Scopes.Select(s => s.ID)).ToArray();
    int[] toRemove = issue.Scopes.Select(s => s.ID).Except(relatedScopes).ToArray();
    

    Now for toAdd you do this:

    foreach(int id in toAdd)
    {
       var scope = new Scope{Id = id};
       edmx.Scopes.Attach(scope);
       issue.Scopes.Add(scope);
    }
    

    And for each scope you need to remove

    foreach(int id in toRemove)
    {
       issue.Scopes.Remove(issue.Scopes.Single(s => s.ID == id));
    }
    

    By now the correct relationships should be formed.

    Hope this helps

    Alex

    Microsoft

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

Sidebar

Related Questions

I have a many-to-many relationship between User and Task model. A task can have
I have a many-to-many relationship between two tables, let's say Friends and Foods. If
I have a many-to-many relationship between users and groups and I have a table
I have a many-to-many relationship between User s and Task s. I want the
I have a one to many relationship between two tables. The many table contains
I have a one-to-many relationship between two classes for this situation. I have a
I have a one-to-many relationship between Foo and Bar and I cannot perform an
Let's say I have many-to-many relationship (using the ActiveRecord attribute HasAndBelongsToMany) between Posts and
I have two entities Foo and Bar with a Many to Many relationship between
i have many to many relationship between employee and group. following linq statement int[]

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.