Summary
A single SaveChanges that removes an entity and adds another with the same primary key fails with a duplicate key error (E11000 on id). Relational providers send one UPDATE for this case, so the same code succeeds there.
Reproduction
var old = db.Things.Single(t => t.Id == id); db.Remove(old); db.Add(new Thing { Id = id, Code = "other" }); db.SaveChanges(); // MongoBulkWriteException: E11000 duplicate key error ... index: _id_
Cause
EF Core pairs the two entries (the Added entry's SharedIdentityEntry is the Deleted one) and leaves the Deleted entry out of the entries to save, as the relational providers then send one UPDATE. The provider only sees the Added entry, builds an InsertOneModel, and collides with the document that is still stored. No delete is ever sent.
Fix
Save such a pair as one ReplaceOne: the filter is the new key plus the removed entity's original concurrency token values (so a changed or deleted document is a DbUpdateConcurrencyException, never an upsert), the replacement is the new entity's whole document, and a row version continues from the replaced one. SaveChanges also counts updates by matched documents rather than modified ones, so an update that writes the values already stored returns 1, as the relational providers do.
Ported from ajcvickers/mongo-efcore-provider#114 (fork issue #109).