title: Update a many-to-many relation in Entity Framework Core
body: <p>I am trying to update a <code>many-to-many</code> relation in a <strong>ASP.NET Core MVC</strong> controller using <strong>Entity Framework Core</strong>. I managed to get this working for adding to the relation, but not updating (leads to a duplicate key error, if I just open/save the entity).</p>
  
  <p>How can I remove the relations from the database before updating/inserting new relations in an efficient way?</p>
  
  <pre><code>public async Task&lt;IActionResult&gt; Edit(int id, [Bind("Id,Name,SalesClerkIds")] Plant plant)
  {
          if (id != plant.Id)
          {
              return NotFound();
          }
  
          if (ModelState.IsValid)
          {
              try
              {
                  plant.SalesClerks = new List&lt;PlantSalesClerk&gt;();
  
                  if (plant.SalesClerkIds != null)
                  {
                      foreach (var scId in plant.SalesClerkIds)
                      {
                          plant.SalesClerks.Add(new PlantSalesClerk()
                          {
                              Plant = plant,
                              User = _context.Users.FirstOrDefault(u =&gt; u.Id == scId)
                          });
                      }
                  }
  
                  _context.Update(plant);
  
                  await _context.SaveChangesAsync();
              }
              catch (DbUpdateConcurrencyException)
              {
                  if (!PlantExists(plant.Id))
                  {
                      return NotFound();
                  }
                  else
                  {
                      throw;
                  }
              }
              return RedirectToAction(nameof(Index));
          }
  
          return View(plant);
    }
  </code></pre>