dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.81k stars 3.2k forks source link

Support OriginalValues and GetDatabaseValues for shared entity entries #19328

Open ItsSmiffy opened 4 years ago

ItsSmiffy commented 4 years ago

I'm in the process of creating an audit log for changed entities/properties but I cannot seem to get original values from an Owned Entity property once that Owned Entity has been replaced by a new instance.

Some of my Entities have properties which are Value Object / Owned Entities (and some of those have nested owned entities). I seem to have hit a blocker whereby I cannot retrieve the old value of an owned entity property once the owning Entity has replaced the owned entity with a new one.

The Owned Entity OriginalValues collection or the call to .GetDatabaseValues() returns the new Owned Entity instance, not the original one as is in the database (n.b. saveChanges has not yet been called).

It is possible to get the original values of an owned entity, even when the owned entity has been replaced by a new instance of that type?

EF Core version: 2.2.6 Database provider: Pomelo (v.2.2.6) Target framework: .NET Framework 4.6 Operating system: Win 10 IDE: Visual Studio 2019 16.4.1

ajcvickers commented 4 years ago

@ItsSmiffy The original values are not available because the original entity is marked as Deleted, while the new entity is marked as Added. However, due to the way owned entities are used it would be worthwhile to add support for getting original values this case. Putting this on the backlog to consider for a future release.

HaisojYellams commented 4 years ago

From the comment above, it sounds like when a Value Object (owned type) is replaced on an entity, the ChangeTracker should have two EntityEntries for that property: one for the old one (with an EntityState.Deleted state) and the new one (with an EntityState.Added state). Am I understanding that correctly?

In working with EF Core 5, I have not found this to be the case. That is, if I replace an existing Value Object with a new one, I only get an 'Added' entry in the change tracker - no 'Deleted' entry. Is this the intended behaviour?

ajcvickers commented 4 years ago

@HaisojYellams Currently what you see is the intended behavior. That may change after this feature is implemented, but that is yet to be determined.

Lobosque commented 3 years ago

Our modeling relies heavily on owned entities and we are also being affected by this shortcoming.