Skip to content

Commit 3eabbaf

Browse files
Fix in-memory corruption of nested owned entities after SaveChanges when navigation is replaced (#37787)
Fixes #38095 Co-authored-by: AndriySvyryd <6539701+AndriySvyryd@users.noreply.github.com>
1 parent 150afc9 commit 3eabbaf

5 files changed

Lines changed: 123 additions & 4 deletions

File tree

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

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,11 @@ private bool PaintAction(
102102
SetReferenceLoaded(node);
103103

104104
var internalEntityEntry = node.GetInfrastructure();
105-
if (internalEntityEntry.EntityState != EntityState.Detached
105+
var sourceEntry = node.SourceEntry?.GetInfrastructure();
106+
107+
if ((internalEntityEntry.EntityState != EntityState.Detached
108+
&& (internalEntityEntry.EntityState != EntityState.Deleted
109+
|| sourceEntry?.SharedIdentityEntry == null))
106110
|| (_visited != null && _visited.Contains(internalEntityEntry.Entity)))
107111
{
108112
return false;
@@ -114,7 +118,7 @@ private bool PaintAction(
114118

115119
if (internalEntityEntry.StateManager.ResolveToExistingEntry(
116120
internalEntityEntry,
117-
node.InboundNavigation, node.SourceEntry?.GetInfrastructure()))
121+
node.InboundNavigation, sourceEntry))
118122
{
119123
(_visited ??= new HashSet<object>(ReferenceEqualityComparer.Instance)).Add(internalEntityEntry.Entity);
120124
}
@@ -139,7 +143,10 @@ private async Task<bool> PaintActionAsync(
139143
SetReferenceLoaded(node);
140144

141145
var internalEntityEntry = node.GetInfrastructure();
142-
if (internalEntityEntry.EntityState != EntityState.Detached
146+
var sourceEntry = node.SourceEntry?.GetInfrastructure();
147+
if ((internalEntityEntry.EntityState != EntityState.Detached
148+
&& (internalEntityEntry.EntityState != EntityState.Deleted
149+
|| sourceEntry?.SharedIdentityEntry == null))
143150
|| (_visited != null && _visited.Contains(internalEntityEntry.Entity)))
144151
{
145152
return false;
@@ -151,7 +158,7 @@ private async Task<bool> PaintActionAsync(
151158

152159
if (internalEntityEntry.StateManager.ResolveToExistingEntry(
153160
internalEntityEntry,
154-
node.InboundNavigation, node.SourceEntry?.GetInfrastructure()))
161+
node.InboundNavigation, sourceEntry))
155162
{
156163
(_visited ??= []).Add(internalEntityEntry.Entity);
157164
}

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1208,6 +1208,14 @@ public virtual void CascadeChanges(bool force)
12081208
/// </summary>
12091209
public virtual void CascadeDelete(InternalEntityEntry entry, bool force, IEnumerable<IForeignKey>? foreignKeys = null)
12101210
{
1211+
// When an owned entity is replaced (e.g., via record 'with' expression), the old entry is
1212+
// marked Deleted and a new entry with the same key is linked via SharedIdentityEntry.
1213+
// Skip cascade from the old entry since the replacement handles its own dependents.
1214+
if (entry.SharedIdentityEntry != null)
1215+
{
1216+
return;
1217+
}
1218+
12111219
var doCascadeDelete = force || CascadeDeleteTiming != CascadeTiming.Never;
12121220
var principalIsDetached = entry.EntityState == EntityState.Detached;
12131221

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

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3671,6 +3671,67 @@ public virtual Task Edit_single_property_with_non_ascii_characters()
36713671
Assert.Equal("测试1", result.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf.SomethingSomething);
36723672
});
36733673

3674+
[ConditionalFact]
3675+
public virtual Task Replace_json_reference_root_preserves_nested_owned_entities_in_memory()
3676+
=> TestHelpers.ExecuteWithStrategyInTransactionAsync(
3677+
CreateContext,
3678+
UseTransaction,
3679+
async context =>
3680+
{
3681+
var query = await context.JsonEntitiesBasic.ToListAsync();
3682+
var entity = query.Single();
3683+
3684+
// Save original leaf value
3685+
var originalLeaf = entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf;
3686+
var originalLeafValue = originalLeaf.SomethingSomething;
3687+
3688+
// Replace the owned reference with a new instance that shares nested reference navigations
3689+
var oldRoot = entity.OwnedReferenceRoot;
3690+
entity.OwnedReferenceRoot = new JsonOwnedRoot
3691+
{
3692+
Name = "Modified",
3693+
Number = oldRoot.Number,
3694+
Names = oldRoot.Names,
3695+
Numbers = oldRoot.Numbers,
3696+
OwnedReferenceBranch = new JsonOwnedBranch
3697+
{
3698+
Id = oldRoot.OwnedReferenceBranch.Id,
3699+
Date = oldRoot.OwnedReferenceBranch.Date,
3700+
Enum = oldRoot.OwnedReferenceBranch.Enum,
3701+
Fraction = oldRoot.OwnedReferenceBranch.Fraction,
3702+
NullableEnum = oldRoot.OwnedReferenceBranch.NullableEnum,
3703+
Enums = oldRoot.OwnedReferenceBranch.Enums,
3704+
NullableEnums = oldRoot.OwnedReferenceBranch.NullableEnums,
3705+
OwnedReferenceLeaf = originalLeaf,
3706+
OwnedCollectionLeaf = [],
3707+
},
3708+
OwnedCollectionBranch = [],
3709+
};
3710+
3711+
// Before DetectChanges, leaf should be accessible
3712+
Assert.Same(originalLeaf, entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf);
3713+
3714+
context.ChangeTracker.DetectChanges();
3715+
3716+
// After DetectChanges, leaf should still be accessible
3717+
Assert.NotNull(entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf);
3718+
3719+
ClearLog();
3720+
await context.SaveChangesAsync();
3721+
3722+
// After SaveChanges, nested owned entities should still be accessible in memory
3723+
Assert.NotNull(entity.OwnedReferenceRoot.OwnedReferenceBranch);
3724+
Assert.NotNull(entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf);
3725+
Assert.Equal(originalLeafValue, entity.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf.SomethingSomething);
3726+
},
3727+
async context =>
3728+
{
3729+
var result = await context.Set<JsonEntityBasic>().SingleAsync();
3730+
Assert.Equal("Modified", result.OwnedReferenceRoot.Name);
3731+
Assert.NotNull(result.OwnedReferenceRoot.OwnedReferenceBranch);
3732+
Assert.NotNull(result.OwnedReferenceRoot.OwnedReferenceBranch.OwnedReferenceLeaf);
3733+
});
3734+
36743735
public void UseTransaction(DatabaseFacade facade, IDbContextTransaction transaction)
36753736
=> facade.UseTransaction(transaction.GetDbTransaction());
36763737

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3274,6 +3274,28 @@ FROM [JsonEntitiesAllTypes] AS [j]
32743274
""");
32753275
}
32763276

3277+
public override async Task Replace_json_reference_root_preserves_nested_owned_entities_in_memory()
3278+
{
3279+
await base.Replace_json_reference_root_preserves_nested_owned_entities_in_memory();
3280+
3281+
AssertSql(
3282+
"""
3283+
@p0='{"Id":0,"Name":"Modified","Names":["e1_r1","e1_r2"],"Number":10,"Numbers":[-2147483648,-1,0,1,2147483647],"OwnedCollectionBranch":[],"OwnedReferenceBranch":{"Date":"2100-01-01T00:00:00","Enum":-1,"Enums":[-1,-1,2],"Fraction":10.0,"Id":88,"NullableEnum":null,"NullableEnums":[null,-1,2],"OwnedCollectionLeaf":[],"OwnedReferenceLeaf":{"SomethingSomething":"e1_r_r_r"}}}' (Nullable = false) (Size = 367)
3284+
@p1='1'
3285+
3286+
SET IMPLICIT_TRANSACTIONS OFF;
3287+
SET NOCOUNT ON;
3288+
UPDATE [JsonEntitiesBasic] SET [OwnedReferenceRoot] = @p0
3289+
OUTPUT 1
3290+
WHERE [Id] = @p1;
3291+
""",
3292+
//
3293+
"""
3294+
SELECT TOP(2) [j].[Id], [j].[EntityBasicId], [j].[Name], [j].[OwnedCollectionRoot], [j].[OwnedReferenceRoot]
3295+
FROM [JsonEntitiesBasic] AS [j]
3296+
""");
3297+
}
3298+
32773299
protected override void ClearLog()
32783300
=> Fixture.TestSqlLoggerFactory.Clear();
32793301

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2408,6 +2408,27 @@ public override Task Edit_single_property_collection_of_collection_of_nullable_i
24082408
public override Task Edit_single_property_collection_of_collection_of_single()
24092409
=> Assert.ThrowsAsync<ArgumentOutOfRangeException>(base.Edit_single_property_collection_of_collection_of_single);
24102410

2411+
public override async Task Replace_json_reference_root_preserves_nested_owned_entities_in_memory()
2412+
{
2413+
await base.Replace_json_reference_root_preserves_nested_owned_entities_in_memory();
2414+
2415+
AssertSql(
2416+
"""
2417+
@p0='{"Id":0,"Name":"Modified","Names":["e1_r1","e1_r2"],"Number":10,"Numbers":[-2147483648,-1,0,1,2147483647],"OwnedCollectionBranch":[],"OwnedReferenceBranch":{"Date":"2100-01-01 00:00:00","Enum":-1,"Enums":[-1,-1,2],"Fraction":"10.0","Id":88,"NullableEnum":null,"NullableEnums":[null,-1,2],"OwnedCollectionLeaf":[],"OwnedReferenceLeaf":{"SomethingSomething":"e1_r_r_r"}}}' (Nullable = false) (Size = 369)
2418+
@p1='1'
2419+
2420+
UPDATE "JsonEntitiesBasic" SET "OwnedReferenceRoot" = @p0
2421+
WHERE "Id" = @p1
2422+
RETURNING 1;
2423+
""",
2424+
//
2425+
"""
2426+
SELECT "j"."Id", "j"."EntityBasicId", "j"."Name", "j"."OwnedCollectionRoot", "j"."OwnedReferenceRoot"
2427+
FROM "JsonEntitiesBasic" AS "j"
2428+
LIMIT 2
2429+
""");
2430+
}
2431+
24112432
protected override void ClearLog()
24122433
=> Fixture.TestSqlLoggerFactory.Clear();
24132434

0 commit comments

Comments
 (0)