title: Entity Framework Core: how to 'wipe and replace' bridge table?
body: <p>Imagine we have a many-to-many relationship (e.g. <code>Product</code> and <code>Category</code> where one product can be in many categories and vice versa). They are identified through a composite key (<code>ProductId</code> / <code>CategoryId</code>).  How do we update this bridge table in Entity Framework Core when we want to persist the changes to the <code>Product</code> aggregate?</p>
  
  <p>In Entity Framework 6, I'd simply wipe out all related data for that product in the bridge table and then re-populate them. This simplifies life as we don't need to manually synchronize changes (inserts, updates, deletes).  Just wipe and replace.</p>
  
  <p>How do we do this in Entity Framework Core?  Here's what I tried:</p>
  
  <pre><code>context.ProductCategories.RemoveRange(product.Categories);
  context.ProductCategories.AddRange(updatedProductCategories);
  </code></pre>
  
  <p>This results in an exception due to duplicate composite key:</p>
  
  <blockquote>
    <p>InvalidOperationException: The instance of entity type 'ProductCategory' cannot be tracked because another instance of this
    type with the same key is already being tracked. When adding new
    entities, for most key types a unique temporary key value will be
    created if no key is set (i.e. if the key property is assigned the
    default value for its type). If you are explicitly setting key values
    for new entities, ensure they do not collide with existing entities or
    temporary values generated for other new entities. When attaching
    existing entities, ensure that only one entity instance with a given
    key value is attached to the context.</p>
  </blockquote>
  
  <p>How do we remove a composite key entity from the context so that we can add another one?</p>
  
  <p>The only way I got this to work so far is to synchronize all changes (deletes, updates, inserts), but it would be much simpler to just wipe and replace.</p>