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

  • Home
  • SEARCH
  • 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 8532465
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T09:43:18+00:00 2026-06-11T09:43:18+00:00

I’m using EF Code First with the following configuration protected override void OnModelCreating(DbModelBuilder modelBuilder)

  • 0

I’m using EF Code First with the following configuration

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<UserProfile>()
        .HasMany(x => x.TeamLeaders)
        .WithMany()
        .Map(m => m.MapLeftKey("UserId")
        .MapRightKey("TeamLeaderId")
        .ToTable("UserTeamLeaders"));
}

TeamLeaders is an ICollection of Users i.e. it is a self referencing many-many relationship.

In plain English, a user can have more than one team leader. This configuration appears to be correct, as it creates the duel FK/PK link table as I would expect.

I have an MVC4 application that allows editing, adding and removal of team leaders from the collection.

In my controller, I originally had the following:

    var original = context.UserProfiles
        .Include("TeamLeaders")
        .Single(x => x.UserId == model.UserId);

    context.Entry(original).CurrentValues.SetValues(model);

However, that last line was failing to mark the TeamLeaders collection as updated, and when I called SaveChanges(), no changes were recorded.

Instead I wrote a simple CopyProperties method on my User class, which uses reflection to manually copy the properties across, so in my controller I now have:

    var original = context.UserProfiles
        .Include("TeamLeaders")
        .Single(x => x.UserId == model.UserId);

    //context.Entry(original).CurrentValues.SetValues(model);

    original.CopyProperties(model);

However, this goes too far, and SaveChanges attempts to add a new user to the system matching the profile of the selected team leader.

Can anyone advise as to which part of this I am doing wrong? I am not sure whether I need to update the mappings, or change the way I copy properties from the view model to the model

  • 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-11T09:43:20+00:00Added an answer on June 11, 2026 at 9:43 am

    You must modify the loaded TeamLeaders collection in the original user according to your changes so that change detection can recognize which leaders have been removed and which have been added. When you call SaveChanges then EF will write the appropriate DELETE and INSERT statements for the join table based on the detected changes. The simplest way would look like this:

    var original = context.UserProfiles
        .Include("TeamLeaders")
        .Single(x => x.UserId == model.UserId);
    
    original.TeamLeaders.Clear();
    foreach (var teamLeader in model.TeamLeaders)
    {
        var user = context.UserProfiles.Find(teamLeader.UserId);
        if (user != null)
            original.TeamLeaders.Add(user)
    }
    context.SaveChanges();
    

    Find will fetch the team leaders from the context if they are already loaded. If they aren’t loaded it will query the database.

    If you want to avoid additional queries you can attach the team leaders manually to the context:

    var original = context.UserProfiles
        .Include("TeamLeaders")
        .Single(x => x.UserId == model.UserId);
    
    original.TeamLeaders.Clear();
    foreach (var teamLeader in model.TeamLeaders)
    {
        var user = context.UserProfiles.Local
            .SingleOrDefault(o => o.UserId == teamLeader.UserId);
        if (user == null)
        {
            user = new User { UserId = teamLeader.UserId };
            context.UserProfiles.Attach(user);
        }
        original.TeamLeaders.Add(user)
    }
    context.SaveChanges();
    

    Except the first query to load the original here is no further database query involved.

    BTW: You should be able to use the strongly typed Include version with EF Code First:

    Include(u => u.TeamLeaders)
    

    You just need using System.Data.Entity; in your code file to get access to this version.

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

Sidebar

Related Questions

I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
We're building an app, our first using Rails 3, and we're having to build
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
I'm making a simple page using Google Maps API 3. My first. One marker
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am reading a book about Javascript and jQuery and using one of the
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function

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.