Description
Problem:
I need to execute code when a new entity gets added to the dbContext/ChangeTracker but before the EF Core base code runs.
One way which I am currently using is that I derive and override the add-methods on some classes (dbContext, dbset, etc. etc. ). I execute my code and then call the base.AddXY() methods. This may work but is not a clear/nice solution because its way to complex to implement (code-generation manipulation while scaffolding) and new methods could be added and therefore needed to be overriden as well etc. so this approach is bound to break in the future.
Requested feature/solution:
A clear solution could be to introduce a new event to the ChangeTracker which gets fired when an entity is about to get tracked (before it actually gets added to the dbContext/ChangeTracker). An useful information on the eventargs could be why or from which source the entity is about to get tracked (add-operation, loading from DB, etc. ).
Right now there is only the "ChangeTracker.Tracked"-Events which gets fired when the entity got added (after all the base EF Core code has run) => https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.changetracking.changetracker.tracked?view=efcore-5.0
Activity
optiks commentedon Jan 6, 2022
Can you elaborate on why you need to run code before tracking?
marcelgoldstein commentedon Jan 6, 2022
I have SQL tables with composite primary keys. Some of them also have a column ID which is the last of the columns participating in the composite key. This ID column gets incremented, but not by the SQL server (identity column with auto-increment) natively. It gets its value from the code executed on SaveChanges just before the EF Core code generates the SQL and runs it on the SQL server.
When instantiating an entity I populate the composite key properties except the ID property because it needs to be set to a unique value and therefore gets calculated by my base-code (not in each viewmodel) when adding it to the DbContext. The calculation of this ID value cant be the final one used on the SQL server because it maybe saved later (and having multiple changes from other places on the database), so the ID value gets an just for the ChangeTracker uniquely value at this point (decrementing from -1).
The whole composite key needs to be unique when adding the entity to the DbContext because EF Core snapshots the "identity" of the entity at this point and therefore would throw an exception if a second entity with the same composite key values would get added.
This "identity-snapshot-mechanic" is the reason I need to be able to execute base-code before it gets added to the ChangeTracker. Otherwise my entities would not have an unique identity from the ChangeTracker perspective and it would throw exceptions.
I hope that makes sense.
New ChangeTracker events
New ChangeTracker events
New ChangeTracker events
New ChangeTracker events
10 remaining items