I have an interface that many of my code-first entities implement:
public interface IRecordTracking
{
DateTime CreateDate { get;set; }
DateTime UpdateDate { get;set; }
}
I also have a repository sitting in front of my DbContext with Add / Update methods with the following code:
Add:
if (item is IRecordTracking tracking)
tracking.CreateDate = DateTime.UtcNow;
Update:
if (item is IRecordTracking tracking)
tracking.UpdateDate = DateTime.UtcNow;
My problem is, I'm finding a scenario where I'm creating a whole chain of entities:
- Sponsor
- SponsorID
- ...
- EntityID
- Entity
- EntityID
- Addresses
- ...
- CreateDate
- UpdateDate
As you can see, the update/create is on the child property Entity.
When I call Add or Update on my repository, I'm passing the Sponsor object, but not the entity (except as a child property). So my check if "item is IRecordTracking" is false.
My question(s) are:
- Is it possible on the DbContext to intercept all inserts/updates and run this logic there?
- Or, is there a clean/efficient(ish) way of walking up the property tree and checking for types that implement
IRecordTracking? This way, my repository (RepositoryBase classs) keeps the logic for this, but it checks all children...
Thanks