Skip to content

Commit e9ba983

Browse files
Preserve matched complex collection ordinals during change detection
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
1 parent c8906e2 commit e9ba983

5 files changed

Lines changed: 91 additions & 1 deletion

File tree

‎.agents/skills/change-tracking/SKILL.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Manages entity states and detects changes for `SaveChanges()`.
2222

2323
- Snapshot and notification strategies both call `SetPropertyModified()` to keep property flags and entity state consistent.
2424
- `SetEntityState()` validates values, updates flags and complex entries, changes state, then runs manager bookkeeping hooks.
25+
- `MoveComplexCollectionEntry` shifts intervening slots. When matching a reused element from an earlier unmatched slot, preserve the ordinals of entries already matched between the two slots.
2526

2627
## Shared-Identity Replacement
2728

‎src/EFCore/ChangeTracking/Internal/ChangeDetector.cs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -497,7 +497,13 @@ public bool DetectComplexCollectionChanges(InternalEntryBase entry, IComplexProp
497497
|| currentNulls.Contains(originalEntry.Ordinal)
498498
|| added.Contains(originalEntry.Ordinal),
499499
$"Expected the entry that was previously at {originalEntry.Ordinal} to have been encountered at an ordinal before {i}.");
500-
entry.MoveComplexCollectionEntry(complexProperty, originalEntry.Ordinal, i);
500+
var previousOrdinal = originalEntry.Ordinal;
501+
entry.MoveComplexCollectionEntry(complexProperty, previousOrdinal, i);
502+
if (previousOrdinal < i - 1)
503+
{
504+
// Swap with the earlier unmatched slot without shifting entries already matched in between.
505+
entry.MoveComplexCollectionEntry(complexProperty, i - 1, previousOrdinal);
506+
}
501507

502508
changesFound = true;
503509
}

‎test/EFCore.Relational.Specification.Tests/Update/ComplexCollectionJsonUpdateTestBase.cs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,45 @@ public virtual Task Save_nested_complex_collection_with_nullable_property(bool a
7878
}
7979
});
8080

81+
[Fact]
82+
public virtual Task Prepend_and_evict_json_complex_collection_element_after_detect_changes()
83+
=> TestHelpers.ExecuteWithStrategyInTransactionAsync(
84+
CreateContext,
85+
UseTransaction,
86+
async context =>
87+
{
88+
var company = await context.Companies.OrderBy(c => c.Id).FirstAsync().ConfigureAwait(false);
89+
var widget = await context.StructWidgets.SingleAsync().ConfigureAwait(false);
90+
company.Contacts = [new() { Name = "t0" }, new() { Name = "t1" }, new() { Name = "t2" }, new() { Name = "t3" }];
91+
widget.Data = new StructData
92+
{
93+
Label = "S1",
94+
Tags = [new() { Value = "t0" }, new() { Value = "t1" }, new() { Value = "t2" }, new() { Value = "t3" }]
95+
};
96+
await context.SaveChangesAsync().ConfigureAwait(false);
97+
},
98+
async context =>
99+
{
100+
var company = await context.Companies.OrderBy(c => c.Id).FirstAsync().ConfigureAwait(false);
101+
var widget = await context.StructWidgets.SingleAsync().ConfigureAwait(false);
102+
company.Contacts = [new() { Name = "new" }, .. company.Contacts!.Take(3)];
103+
widget.Data = new StructData { Label = widget.Data.Label, Tags = [new() { Value = "new" }, .. widget.Data.Tags.Take(3)] };
104+
105+
context.ChangeTracker.DetectChanges();
106+
ClearLog();
107+
await context.SaveChangesAsync().ConfigureAwait(false);
108+
},
109+
async context =>
110+
{
111+
using (SuspendRecordingEvents())
112+
{
113+
var company = await context.Companies.OrderBy(c => c.Id).FirstAsync().ConfigureAwait(false);
114+
var widget = await context.StructWidgets.SingleAsync().ConfigureAwait(false);
115+
Assert.Equal(["new", "t0", "t1", "t2"], company.Contacts!.Select(c => c.Name));
116+
Assert.Equal(["new", "t0", "t1", "t2"], widget.Data.Tags.Select(t => t.Value));
117+
}
118+
});
119+
81120
[Fact]
82121
public virtual Task Add_element_to_complex_collection_mapped_to_json()
83122
=> TestHelpers.ExecuteWithStrategyInTransactionAsync(

‎test/EFCore.SqlServer.FunctionalTests/Update/ComplexCollectionJsonUpdateSqlServerTest.cs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,27 @@ OUTPUT 1
2727
""");
2828
}
2929

30+
public override async Task Prepend_and_evict_json_complex_collection_element_after_detect_changes()
31+
{
32+
await base.Prepend_and_evict_json_complex_collection_element_after_detect_changes().ConfigureAwait(false);
33+
34+
AssertSql(
35+
"""
36+
@p0='[{"Name":"new","PhoneNumbers":[]},{"Name":"t0","PhoneNumbers":[]},{"Name":"t1","PhoneNumbers":[]},{"Name":"t2","PhoneNumbers":[]}]' (Nullable = false) (Size = 130)
37+
@p1='1'
38+
@p2='{"Label":"S1","Tags":[{"Value":"new"},{"Value":"t0"},{"Value":"t1"},{"Value":"t2"}]}' (Nullable = false) (Size = 84)
39+
@p3='1'
40+
41+
SET NOCOUNT ON;
42+
UPDATE [Companies] SET [Contacts] = @p0
43+
OUTPUT 1
44+
WHERE [Id] = @p1;
45+
UPDATE [StructWidgets] SET [Data] = @p2
46+
OUTPUT 1
47+
WHERE [Id] = @p3;
48+
""");
49+
}
50+
3051
public override async Task Add_element_to_complex_collection_mapped_to_json()
3152
{
3253
await base.Add_element_to_complex_collection_mapped_to_json();

‎test/EFCore.Sqlite.FunctionalTests/Update/ComplexCollectionJsonUpdateSqliteTest.cs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,29 @@ public override async Task Save_nested_complex_collection_with_nullable_property
2525
""");
2626
}
2727

28+
public override async Task Prepend_and_evict_json_complex_collection_element_after_detect_changes()
29+
{
30+
await base.Prepend_and_evict_json_complex_collection_element_after_detect_changes().ConfigureAwait(false);
31+
32+
AssertSql(
33+
"""
34+
@p0='[{"Name":"new","PhoneNumbers":[]},{"Name":"t0","PhoneNumbers":[]},{"Name":"t1","PhoneNumbers":[]},{"Name":"t2","PhoneNumbers":[]}]' (Nullable = false) (Size = 130)
35+
@p1='1'
36+
37+
UPDATE "Companies" SET "Contacts" = @p0
38+
WHERE "Id" = @p1
39+
RETURNING 1;
40+
""",
41+
"""
42+
@p0='{"Label":"S1","Tags":[{"Value":"new"},{"Value":"t0"},{"Value":"t1"},{"Value":"t2"}]}' (Nullable = false) (Size = 84)
43+
@p1='1'
44+
45+
UPDATE "StructWidgets" SET "Data" = @p0
46+
WHERE "Id" = @p1
47+
RETURNING 1;
48+
""");
49+
}
50+
2851
public override async Task Add_element_to_complex_collection_mapped_to_json()
2952
{
3053
await base.Add_element_to_complex_collection_mapped_to_json();

0 commit comments

Comments
 (0)