diff --git a/src/EFCore/ChangeTracking/Internal/ChangeDetector.cs b/src/EFCore/ChangeTracking/Internal/ChangeDetector.cs index cc56a5cff7e..e4ad479da3d 100644 --- a/src/EFCore/ChangeTracking/Internal/ChangeDetector.cs +++ b/src/EFCore/ChangeTracking/Internal/ChangeDetector.cs @@ -14,6 +14,9 @@ namespace Microsoft.EntityFrameworkCore.ChangeTracking.Internal; /// public class ChangeDetector : IChangeDetector { + private static readonly bool UseOldBehavior39450 = + AppContext.TryGetSwitch("Microsoft.EntityFrameworkCore.Issue39450", out var enabled) && enabled; + private readonly IDiagnosticsLogger _logger; private readonly ILoggingOptions _loggingOptions; private bool _inCascadeDelete; @@ -492,9 +495,18 @@ public bool DetectComplexCollectionChanges(InternalEntryBase entry, IComplexProp else { Check.DebugAssert( - originalEntry.Ordinal > i || currentNulls.Contains(originalEntry.Ordinal), + originalEntry.Ordinal > i + || currentNulls.Contains(originalEntry.Ordinal) + || added.Contains(originalEntry.Ordinal), $"Expected the entry that was previously at {originalEntry.Ordinal} to have been encountered at an ordinal before {i}."); - entry.MoveComplexCollectionEntry(complexProperty, originalEntry.Ordinal, i); + var previousOrdinal = originalEntry.Ordinal; + entry.MoveComplexCollectionEntry(complexProperty, previousOrdinal, i); + if (!UseOldBehavior39450 + && previousOrdinal < i - 1) + { + // Swap with the earlier unmatched slot without shifting entries already matched in between. + entry.MoveComplexCollectionEntry(complexProperty, i - 1, previousOrdinal); + } changesFound = true; } diff --git a/test/EFCore.Relational.Specification.Tests/Update/ComplexCollectionJsonUpdateTestBase.cs b/test/EFCore.Relational.Specification.Tests/Update/ComplexCollectionJsonUpdateTestBase.cs index 3554d76473f..63be421ccb8 100644 --- a/test/EFCore.Relational.Specification.Tests/Update/ComplexCollectionJsonUpdateTestBase.cs +++ b/test/EFCore.Relational.Specification.Tests/Update/ComplexCollectionJsonUpdateTestBase.cs @@ -71,6 +71,47 @@ public virtual Task Save_nested_complex_collection_with_nullable_property(bool a } }); + [Fact] + public virtual Task Prepend_and_evict_json_complex_collection_element_after_detect_changes() + => TestHelpers.ExecuteWithStrategyInTransactionAsync( + CreateContext, + UseTransaction, + async context => + { + var company = await context.Companies.OrderBy(c => c.Id).FirstAsync().ConfigureAwait(false); + var widget = await context.Widgets.SingleAsync().ConfigureAwait(false); + company.Contacts = [new() { Name = "t0" }, new() { Name = "t1" }, new() { Name = "t2" }, new() { Name = "t3" }]; + widget.Deep = new DeepData + { + Mid = new MiddleData + { + Items = [new() { Title = "t0" }, new() { Title = "t1" }, new() { Title = "t2" }, new() { Title = "t3" }] + } + }; + await context.SaveChangesAsync().ConfigureAwait(false); + }, + async context => + { + var company = await context.Companies.OrderBy(c => c.Id).FirstAsync().ConfigureAwait(false); + var widget = await context.Widgets.SingleAsync().ConfigureAwait(false); + company.Contacts = [new() { Name = "new" }, .. company.Contacts!.Take(3)]; + widget.Deep.Mid.Items = [new() { Title = "new" }, .. widget.Deep.Mid.Items.Take(3)]; + + context.ChangeTracker.DetectChanges(); + ClearLog(); + await context.SaveChangesAsync().ConfigureAwait(false); + }, + async context => + { + using (SuspendRecordingEvents()) + { + var company = await context.Companies.OrderBy(c => c.Id).FirstAsync().ConfigureAwait(false); + var widget = await context.Widgets.SingleAsync().ConfigureAwait(false); + Assert.Equal(["new", "t0", "t1", "t2"], company.Contacts!.Select(c => c.Name)); + Assert.Equal(["new", "t0", "t1", "t2"], widget.Deep.Mid.Items.Select(i => i.Title)); + } + }); + [Fact] public virtual Task Add_element_to_complex_collection_mapped_to_json() => TestHelpers.ExecuteWithStrategyInTransactionAsync( diff --git a/test/EFCore.SqlServer.FunctionalTests/Update/ComplexCollectionJsonUpdateSqlServerTest.cs b/test/EFCore.SqlServer.FunctionalTests/Update/ComplexCollectionJsonUpdateSqlServerTest.cs index 2bb0604f91a..db4ff933fb5 100644 --- a/test/EFCore.SqlServer.FunctionalTests/Update/ComplexCollectionJsonUpdateSqlServerTest.cs +++ b/test/EFCore.SqlServer.FunctionalTests/Update/ComplexCollectionJsonUpdateSqlServerTest.cs @@ -27,6 +27,27 @@ OUTPUT 1 """); } + public override async Task Prepend_and_evict_json_complex_collection_element_after_detect_changes() + { + await base.Prepend_and_evict_json_complex_collection_element_after_detect_changes().ConfigureAwait(false); + + AssertSql( + """ +@p0='[{"Name":"new","PhoneNumbers":[]},{"Name":"t0","PhoneNumbers":[]},{"Name":"t1","PhoneNumbers":[]},{"Name":"t2","PhoneNumbers":[]}]' (Nullable = false) (Size = 130) +@p1='1' +@p2='{"Mid":{"Items":[{"Title":"new","Inner":[],"Others":[]},{"Title":"t0","Inner":[],"Others":[]},{"Title":"t1","Inner":[],"Others":[]},{"Title":"t2","Inner":[],"Others":[]}]}}' (Nullable = false) (Size = 172) +@p3='1' + +SET NOCOUNT ON; +UPDATE [Companies] SET [Contacts] = @p0 +OUTPUT 1 +WHERE [Id] = @p1; +UPDATE [Widgets] SET [Deep] = @p2 +OUTPUT 1 +WHERE [Id] = @p3; +"""); + } + public override async Task Add_element_to_complex_collection_mapped_to_json() { await base.Add_element_to_complex_collection_mapped_to_json(); diff --git a/test/EFCore.Sqlite.FunctionalTests/Update/ComplexCollectionJsonUpdateSqliteTest.cs b/test/EFCore.Sqlite.FunctionalTests/Update/ComplexCollectionJsonUpdateSqliteTest.cs index f9aff53a33e..df6edd77d7d 100644 --- a/test/EFCore.Sqlite.FunctionalTests/Update/ComplexCollectionJsonUpdateSqliteTest.cs +++ b/test/EFCore.Sqlite.FunctionalTests/Update/ComplexCollectionJsonUpdateSqliteTest.cs @@ -25,6 +25,29 @@ public override async Task Save_nested_complex_collection_with_nullable_property """); } + public override async Task Prepend_and_evict_json_complex_collection_element_after_detect_changes() + { + await base.Prepend_and_evict_json_complex_collection_element_after_detect_changes().ConfigureAwait(false); + + AssertSql( + """ +@p0='[{"Name":"new","PhoneNumbers":[]},{"Name":"t0","PhoneNumbers":[]},{"Name":"t1","PhoneNumbers":[]},{"Name":"t2","PhoneNumbers":[]}]' (Nullable = false) (Size = 130) +@p1='1' + +UPDATE "Companies" SET "Contacts" = @p0 +WHERE "Id" = @p1 +RETURNING 1; +""", + """ +@p0='{"Mid":{"Items":[{"Title":"new","Inner":[],"Others":[]},{"Title":"t0","Inner":[],"Others":[]},{"Title":"t1","Inner":[],"Others":[]},{"Title":"t2","Inner":[],"Others":[]}]}}' (Nullable = false) (Size = 172) +@p1='1' + +UPDATE "Widgets" SET "Deep" = @p0 +WHERE "Id" = @p1 +RETURNING 1; +"""); + } + public override async Task Add_element_to_complex_collection_mapped_to_json() { await base.Add_element_to_complex_collection_mapped_to_json();