Repository navigation
SaveChanges: replace a document when an entity is removed and another added with the same key (Fixes #109) - #114
Merged
Merged
Conversation
… 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>
…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
force-pushed
the
issue-109
branch
from
November 14, 2026 16:15
d698473 to
6e33a2f
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #109.
Problem
A
SaveChangesthat removes an entity and adds another with the same primary key failed withE11000on_id. EF Core pairs the two entries (the Added entry'sSharedIdentityEntryis the Deleted one) and leaves the Deleted one out of the entries to save, as the relational providers then send oneUPDATE. 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
ReplaceOne.MongoUpdate.ConvertAddedsaves 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 aDbUpdateConcurrencyException(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 underAutoTransactionBehavior.Never.ContinueRowVersions, numeric andbyte[]), so a context still holding the old version cannot match a restarted one.MongoUpdate.IsUpdate):MongoUpdateBatch.Modified, the match-count check, the failed-write handling and the bulk-write log counts.MongoUniqueValueOrderertreats a replace as an update that frees the removed document's unique values and takes the new entity's.SaveChangescounts updates by matched documents, not modified ones. MongoDB reports a$setor replace that writes the values already stored asmatched=1, modified=0. Every property was already written (checked on the wire: an entity set toModifiedsends$setof 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.UpdateEntityTestspinned the old 0 and now expects 1.Breaking changes (both in
BREAKING-CHANGES.md)Attach,Remove,Addthe same key) used to insert it by accident and now throwsDbUpdateConcurrencyException, as the relational providers do.SaveChangesreturns 1, not 0, for an update that matches its document but changes nothing (for example an entity set toModifiedwithout 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 fiveUpdate_root_by_collection_replacement_*tests,Save_required_one_to_one_changed_by_reference(GraphUpdatesandProxyGraphUpdates), theFieldMappingbacking-field test, and 21 of the 35KeysWithConvertersinsert 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
RemovethenUpdateof the same key (a Modified entry paired with a Deleted one) is still a$setof the modified properties, as before. Noted inStorage/AGENTS.md, and covered by a unit test and a functional test that records it.Testing
test-allon the branch rebased ontoreleaseat #113: EF8, EF9, EF10 and EF11, Default and NativeOnly, unit, functional and spec: 24 runs, 0 failures. NewReplaceDocumentTests(43 functional cases, sync and async) cover:byte[]row versions;MongoBulkWriteEventData, not the message text).MongoUpdateReplaceTests(unit, no server) checks the write itself: aReplaceOnewith 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 anUpdateOne. It also coversMongoUniqueValueOrderer.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-collapsedKeysWithConverterspins, the stale inventory counts, the publicIUpdateEntry.SharedIdentityEntryuse, 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