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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T06:51:25+00:00 2026-05-28T06:51:25+00:00

I’ve been using EF4 (not code-first) since a year, so I’m not really an

  • 0

I’ve been using EF4 (not code-first) since a year, so I’m not really an expert with it.
I’ve a doubt in using many-to-many relationship regarding save n update.

I read somewhere on stackoverflow (i can’t find the url anymore) that one solution – to update an existing many-to-many relation – is to not declare “virtual” property; but, if i do this way, the engine can’t load dataas with easy loading.

Can you pls explain me the reason? Otherwire, could you please help me in finding some cool docs on this theme?

thx

  • 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-28T06:51:26+00:00Added an answer on May 28, 2026 at 6:51 am

    You can update a many-to-many relationship this way (as an example which gives user 3 the role 5):

    using (var context = new MyObjectContext())
    {
        var user = context.Users.Single(u => u.UserId == 3);
        var role = context.Roles.Single(r => r.RoleId == 5);
    
        user.Roles.Add(role);
    
        context.SaveChanges();
    }
    

    If the User.Roles collection is declared as virtual the line user.Roles.Add(role); will indeed trigger lazy loading which means that all roles for the user are loaded first from the database before you add the new role.

    This is in fact disturbing because you don’t need to load the whole Roles collection to add a new role to the user.

    But this doesn’t mean that you have to remove the virtual keyword and abandon lazy loading altogether. You can just turn off lazy loading in this specific situation:

    using (var context = new MyObjectContext())
    {
        context.ContextOptions.LazyLoadingEnabled = false;
    
        var user = context.Users.Single(u => u.UserId == 3);
        var role = context.Roles.Single(r => r.RoleId == 5);
    
        user.Roles = new List<Role>(); // necessary, if you are using POCOs
        user.Roles.Add(role);
    
        context.SaveChanges();
    }
    

    Edit

    If you want to update the whole roles collection of a user I would prefer to load the original roles with eager loading ( = Include). You need this list anyway to possibly remove some roles, so you don’t need to wait until lazy loading fetches them from the database:

    var newRolsIds = new List<int> { 1, 2, 5 };
    using (var context = new MyObjectContext())
    {
        var user = context.Users.Include("Roles")
            .Single(u => u.UserId == 3);
        // loads user with roles, for example role 3 and 5
    
        var newRoles = context.Roles
            .Where(r => newRolsIds.Contains(r.RoleId))
            .ToList();
    
        user.Roles.Clear();
        foreach (var newRole in newRoles)
            user.Roles.Add(newRole);
    
        context.SaveChanges();
    }
    

    Instead of loading the new roles from the database you can also attach them since you know in the example the key property value. You can also remove exactly the missing roles instead of clearing the whole collection and instead of re-adding the exisiting roles:

    var newRolsIds = new List<int> { 1, 2, 5 };
    using (var context = new MyObjectContext())
    {
        var user = context.Users.Include("Roles")
            .Single(u => u.UserId == 3);
        // loads user with roles, for example role 3 and 5
    
        foreach (var role in user.Roles.ToList())
        {
            // Remove the roles which are not in the list of new roles
            if (!newRoleIds.Contains(role.RoleId))
                user.Roles.Remove(role);
            // Removes role 3 in the example
        }
    
        foreach (var newRoleId in newRoleIds)
        {
            // Add the roles which are not in the list of user's roles
            if (!user.Roles.Any(r => r.RoleId == newRoleId))
            {
                var newRole = new Role { RoleId = newRoleId };
                context.Roles.Attach(newRole);
                user.Roles.Add(newRole);
            }
            // Adds roles 1 and 2 in the example
        }
        // The roles which the user was already in (role 5 in the example)
        // have neither been removed nor added.
    
        context.SaveChanges();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We're building an app, our first using Rails 3, and we're having to build
I'm making a simple page using Google Maps API 3. My first. One marker
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
We are using XSLT to translate a RIXML file to XML. Our RIXML contains

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.