dotnet / dotnet/efcore

Make SharedIdentityEntry visible in EntityEntry to make change tracking owned objects easier.

Open
#29,830 0 comments 0 reactions 0 assignees View on GitHub
area-change-tracking area-dbcontext customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

**Problem I'm trying to solve:**
I'm trying to track the history of changes to an entity with owned value objects.

The issue is that updates to owned value objects are recorded in the ChangeTracker as ADDED new owned objects and DELETED old owned objects and matching the ADDED new object with the correct DELETED old object to record the value change seems impossible with the public API that I could access.

**What I've tried so far:**
Using EF Core 6, I have managed to fetch the correct DELETED entry with the SharedIdentityEntry field of the InternalEntityEntry.
Entry in the code below being the EntityEntry of the base entity that owns value objects, while ownedAddedEntry will contain the new value for the value object and ownedDeletedEntry will contain the old value for the value object.
```
var ownedAddedEntries = Entry.References.Where(r =>
r.TargetEntry != null
&& r.TargetEntry.State == EntityState.Added
&& r.TargetEntry.Metadata.IsOwned());

foreach (var ownedAddedEntry in ownedAddedEntries ) {
var internalEntry = typeof(EntityEntry)
.GetProperty("InternalEntry", BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(ownedAddedEntry.TargetEntry) as InternalEntityEntry;

if (internalEntry is not null) {
var ownedDeletedEntry = internalEntry.SharedIdentityEntry;
/* Compare ownedAddedEntry to ownedDeletedEntry and log changes if necessary) */
}
}
```

**Solution I'd like to see:**
This uses reflection to access the InternalEntityEntry to get access to SharedIdentityEntry, which is bad. Could the SharedIdentityEntry be exposed in the public API of EntityEntry, so that this matching of ADDED and DELETED owned objects would be easier for change tracking? Or is there a better way to currently match the ADDED owned object with the corresponding DELETED owned object without using the internal API?

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.