Skip to content

SaveChanges: replace a document when an entity is removed and another added with the same key (Fixes #109) - #114

Merged
ajcvickers merged 3 commits into
releasefrom
issue-109
Nov 14, 2026
Merged

ajcvickers merged 3 commits into
releasefrom
issue-109

Conversation

@ajcvickers

@ajcvickers ajcvickers commented Nov 14, 2026 •

Copy link
Copy Markdown
Owner

Fixes #109.

Problem

A SaveChanges that removes an entity and adds another with the same primary key failed with E11000 on _id. EF Core pairs the two entries (the Added entry's SharedIdentityEntry is the Deleted one) and leaves the Deleted one out of the entries to save, as the relational providers then send one UPDATE. The provider only saw the Added entry, inserted it, and collided with the document still stored. No delete was ever produced, so write ordering (#102) could not help.

Change

  • One ReplaceOne. MongoUpdate.ConvertAdded saves such a pair as a replace. The filter is the new key plus the removed entity's original concurrency token values, so a document that was changed or deleted since it was loaded is a DbUpdateConcurrencyException (reporting the Added entry), never an upsert. The replacement is the new entity's whole document, so nothing of the old one (properties, owned entities, unmapped elements) survives. The write is atomic: the document is never missing, which matters under AutoTransactionBehavior.Never.
  • Row versions continue from the replaced one (ContinueRowVersions, numeric and byte[]), so a context still holding the old version cannot match a restarted one.
  • Counted as a modification (MongoUpdate.IsUpdate): MongoUpdateBatch.Modified, the match-count check, the failed-write handling and the bulk-write log counts. MongoUniqueValueOrderer treats a replace as an update that frees the removed document's unique values and takes the new entity's.
  • SaveChanges counts updates by matched documents, not modified ones. MongoDB reports a $set or replace that writes the values already stored as matched=1, modified=0. Every property was already written (checked on the wire: an entity set to Modified sends $set of all of them), so the 0 was an artifact of the server's change detection, not of what was written. The relational providers return the matched row, and the concurrency check already treated a match as applied. This is what makes an identical re-add return 1. UpdateEntityTests pinned the old 0 and now expects 1.

Breaking changes (both in BREAKING-CHANGES.md)

  1. A remove and add of the same key now succeeds. A stub that was removed for a document that does not exist (Attach, Remove, Add the same key) used to insert it by accident and now throws DbUpdateConcurrencyException, as the relational providers do.
  2. SaveChanges returns 1, not 0, for an update that matches its document but changes nothing (for example an entity set to Modified without a change).

Spec tests

The overrides that pinned the duplicate-key failure now run the base test: Save_replaced_principal, Can_delete_and_add_for_same_key, Can_change_type_of_pk_to_pk_dependent_by_replacing_with_new_dependent, the five Update_root_by_collection_replacement_* tests, Save_required_one_to_one_changed_by_reference (GraphUpdates and ProxyGraphUpdates), the FieldMapping backing-field test, and 21 of the 35 KeysWithConverters insert tests (EF-X306, now resolved). The other 14 of those (struct key with required dependents) get past the duplicate key and reach the known EF-X305 failure, so they are pinned to that. Inventory counts are updated.

Not changed

  • Remove then Update of the same key (a Modified entry paired with a Deleted one) is still a $set of the modified properties, as before. Noted in Storage/AGENTS.md, and covered by a unit test and a functional test that records it.

Testing

test-all on the branch rebased onto release at #113: EF8, EF9, EF10 and EF11, Default and NativeOnly, unit, functional and spec: 24 runs, 0 failures. New ReplaceDocumentTests (43 functional cases, sync and async) cover:

  • the replace itself and its whole-document semantics;
  • owned entities, composite and value-converted keys, and derived types;
  • concurrency tokens and numeric and byte[] row versions;
  • a document deleted by someone else;
  • a conflicting batch rolling back;
  • unique-value ordering both ways;
  • the log counts;
  • identical re-add and no-op update counts;
  • the bulk-write event payload (one modified write, read from MongoBulkWriteEventData, not the message text).

MongoUpdateReplaceTests (unit, no server) checks the write itself: a ReplaceOne with no upsert, whose filter is the key plus the removed entity's original token (the new entity's value is only in the replacement), that a lone Add is still an insert, and that a Modified entry paired with a Deleted one is still an UpdateOne. It also covers MongoUniqueValueOrderer.AddReplacement: a replace that frees or takes a value, a value it keeps, a null, and a swap (a cycle keeps its order).

Reviewed with /review-provider (storage, spec-conformance, API stability, EF conformance and security reviewers). Their findings are addressed: the 14 mis-collapsed KeysWithConverters pins, the stale inventory counts, the public IUpdateEntry.SharedIdentityEntry use, the missing composite/converted-key, rollback and entry-state tests, the unit tests for the replace write and its ordering, and the event-data log test.

🤖 Generated with Claude Code

ajcvickers and others added 3 commits November 14, 2026 16:14
… added with the same key (Fixes #109)

EF Core pairs the two entries (the Added entry's SharedIdentityEntry is the
Deleted one) and leaves the Deleted one out of the entries to save, as the
relational providers then send one UPDATE. The provider only saw the Added
entry, inserted it, and failed with E11000 on _id because the old document was
still there. Reordering writes cannot help: no delete was ever produced.

- MongoUpdate.ConvertAdded saves such a pair as one ReplaceOne. The filter is the
  new key plus the original concurrency token values of the removed entity (a
  changed or deleted document is a DbUpdateConcurrencyException, never an
  upsert) and the replacement is the new entity's whole document, so nothing of
  the old document survives. A row version continues from the one it replaces,
  so a context holding the old version cannot match a restarted one.
- A replace counts as a modification (MongoUpdate.IsUpdate): MongoUpdateBatch.Modified,
  the match-count check, the failed-write handling and the bulk-write log counts.
  The DbUpdateConcurrencyException reports the Added entry.
- MongoUniqueValueOrderer treats a replace as an update that frees the removed
  document's unique values and takes the new entity's.
- SaveChanges counts updates by matched documents, not modified ones. MongoDB
  reports a $set or replace that writes the values already stored as unmodified,
  so an entity set to Modified without a change, or an identical re-add, returned
  0. The relational providers return the matched row, and the concurrency check
  already treated a match as applied. UpdateEntityTests now expects 1.

Both behavior changes are in BREAKING-CHANGES.md: a remove-and-add of the same
key now succeeds (and a stub removed for a document that does not exist now
throws DbUpdateConcurrencyException instead of inserting), and the returned count
for an update that changes nothing is 1.

Spec tests: the overrides that pinned the duplicate key failure are now plain
pass-throughs (Save_replaced_principal, Can_delete_and_add_for_same_key, the
Update_root_by_collection_replacement_* tests, Save_required_one_to_one_changed_by_reference,
the FieldMapping backing field test, and 21 KeysWithConverters tests). The 14
KeysWithConverters tests with a struct key and required dependents now reach
EF-X305 and are pinned to it. The inventory counts are updated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ocument (Refs #109)

The counter-based byte[] row versions added in #112 are seeded from the removed
entity's original value in ContinueRowVersions, as the numeric ones are.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…a log test (Refs #109)

- MongoUpdateReplaceTests builds the Remove/Add pair in a change tracker and checks
  that it is a ReplaceOne (no upsert) whose filter is the key plus the removed
  entity's original concurrency token values, that a lone Add is an insert, and that
  a Modified entry paired with a Deleted one is still an UpdateOne.
- The same tests cover MongoUniqueValueOrderer.AddReplacement: a replace that frees
  or takes a value is ordered against the updates that take or free it, a value it
  keeps is neither, a null is not a value to conflict on, and a swap is a cycle that
  keeps its order.
- The bulk-write log test reads MongoBulkWriteEventData through a DiagnosticListener
  instead of matching the message text.
- A functional test records that Remove then Update of the same key is still a $set
  of the properties (an element only the old document had stays), as before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@ajcvickers
ajcvickers merged commit f065c69 into release Nov 14, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SaveChanges: removing a document and adding another with the same key fails with a duplicate key error

1 participant