dotnet / dotnet/efcore

Allow reparenting owned entities with nested navigations.

Open
#36,206 4 comments 1 reaction 1 assignee Assigned to @AndriySvyryd View on GitHub
area-change-tracking area-owned-entities area-save-changes customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

### Bug description

## Summary
When moving an entity with owned data from one parent to another in Entity Framework Core, the owned data is unexpectedly deleted during `SaveChanges()`.

## Expected Behavior
The owned data should be preserved when moving an entity between parents.

## Actual Behavior
The owned data becomes null after moving the entity to a new parent.

## Minimal Reproduction

```csharp
public class Parent
{
public int Id { get; set; }
public List Entities { get; set; } = new List();
}

public class EntityWithOwnedData
{
public Parent Parent { get; set; }
public int Id { get; set; }
public OwnedData? Data { get; set; }
}

public class OwnedData
{
public string Value { get; set; }
}

public class TestDbContext : DbContext
{
public DbSet Parents { get; set; }
public DbSet Entities { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.OwnsOne(e => e.Data);
}
}

// Test that demonstrates the issue
var parent1 = new Parent();
var parent2 = new Parent();

var entity = new EntityWithOwnedData
{
Data = new OwnedData { Value = "Test Value" }
};

parent1.Entities.Add(entity);
context.Parents.AddRange(parent1, parent2);
context.SaveChanges();

Assert.NotNull(entity.Data); // ✅ Passes - data exists

// Move entity to new parent
parent1.Entities.Remove(entity);
parent2.Entities.Add(entity);
context.SaveChanges();

Assert.NotNull(entity.Data); // ❌ Fails - data is null
```

## Environment
- Entity Framework Core 9.0.0
- .NET 9.0
- Reproduced on SQLite, PostgreSQL, and SQL Server

The issue occurs specifically when using owned entities in a collection navigation property and moving the containing entity between different parents.

### Your code

```csharp
https://github.com/uflowie/efcore-owned-entity-move-bug
```

### Stack traces

```text

```

### Verbose output

```text

```

### EF Core version

9.0.0

### Database provider

_No response_

### Target framework

_No response_

### Operating system

_No response_

### IDE

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.