title: Updating many to many relationships in Entity Framework
body: <p>I'm able to create a user successfully. I'm now trying to assign some roles to the user during the creation process.</p>
  
  <p>I'm using a database-first approach with Entity Framework. I've tried following some tutorials and looking at other peoples solutions, but can't seem to get it working.</p>
  
  <p>I have 3 tables: <code>User</code>, <code>Role</code>, and <code>UserRole</code> (contains <code>UserId</code> and <code>RoleId</code>).</p>
  
  <p>The relationship between <code>User</code> and <code>Role</code> is many-to-many.</p>
  
  <p><a href="https://i.stack.imgur.com/YaidO.png" rel="nofollow noreferrer">Entity Diagram Showing Relationships</a></p>
  
  <p><a href="https://i.stack.imgur.com/aYt7N.png" rel="nofollow noreferrer">The Create view, which contains checkboxes</a></p>
  
  <p>Database context class:</p>
  
  <pre><code>public partial class MyDBEntities : DbContext
  {
      public MyDBEntities() : base("name=MyDBEntities")
      {
      }
  
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          throw new UnintentionalCodeFirstException();
      }
  
      public virtual DbSet&lt;User&gt; Users { get; set; }
      public virtual DbSet&lt;Role&gt; Roles { get; set; }
  }
  </code></pre>
  
  <p><strong>User.cs:</strong></p>
  
  <pre><code>public partial class User
  {
      public User()
      {
          this.Roles = new HashSet&lt;Role&gt;();
      }
  
      public int Id { get; set; }
      public string Username { get; set; }
      public string Email { get; set; }
      public string Password_hash { get; set; }
  
      public virtual ICollection&lt;Role&gt; Roles { get; set; }
  }
  </code></pre>
  
  <p><strong>Role.cs:</strong></p>
  
  <pre><code>public partial class Role
  {
      public Role()
      {
          this.Users = new HashSet&lt;User&gt;();
      }
  
      public int Id { get; set; }
      public string Name { get; set; }
  
      public virtual ICollection&lt;User&gt; Users { get; set; }
  }
  </code></pre>
  
  <p><strong>[HttpGet] Create():</strong></p>
  
  <pre><code>public ActionResult Create()
  {
          return View(new UserCreateVM
          {
              Roles = db.Roles.Select(x =&gt; new RoleCheckboxVM
              {
                  Id = x.Id,
                  Name = x.Name,
                  IsChecked = false
              }).ToList()
          });
      }
  </code></pre>
  
  <p><strong>[HttpPost] Create():</strong></p>
  
  <pre><code>[HttpPost]
  [ValidateAntiForgeryToken]
  public ActionResult Create(UserCreateVM vm)
  {
          User user = new User();
  
          var selectedRoles = new List&lt;Role&gt;();
  
          foreach (var r in db.Roles)   // we query all the roles in the database
          {
              var checkbox = vm.Roles.Single(x =&gt; x.Id == r.Id);
              checkbox.Name = r.Name; //updates the name on all our checkboxes
  
              if (checkbox.IsChecked) //if checkbox is checked
              {
                  selectedRoles.Add(r); //then we add the role to our selectedRoles
              }
          }
  
          IList&lt;Role&gt; rolesList = user.Roles.ToList();
  
          foreach (var toAdd in selectedRoles.Where(x =&gt; !rolesList.Contains(x))) //if roles is not already added
          {
              rolesList.Add(toAdd); //then we add them to the user roles
          }
  
          if (ModelState.IsValid)
          {
              //We update the data on the object
              user.Username = vm.Username;
              user.Email = vm.Email;
  
              user.SetPassword(vm.Password_hash); //we hash the password
  
              db.Users.Add(user);
              db.SaveChanges();
  
              return RedirectToAction("Index");
          }
  
          return View(vm);
      }
  </code></pre>