I will think about this from the Entity-framework Point of view.
You basically need to do the following :
1- I will define an interface like ITrackable interface, and make my models implement that interface if these models need track the DateCreated and DateModified porperties.
2- Somehow your model know whether it is am Added/Modified entities because this will decide which property to set (Both for Added entity and just DateModified for Modified entities).
3- With your DbContext in Entity-Framework Add an extension method that you need to call when you try to save your entities through SaveChanges or SaveChangesAsync and this method will loop through the tracked entities and set the DateCreated and DateModified properties according to the entity's state.
So your model will look like this:
public class Person : IdentityUser, ITrackable
{
[Required]
public string Name { get; set; }
public Date DateOfBirth { get; set; }
public string Address { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
Where ITrackable looks like
public interface ITrackable
{
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
}
and the extension method will be something like this:
internal static class ContextHelper
{
internal static void SyncObjectsStatePreCommit(this DbContext dbContext)
{
foreach (var dbEntityEntry in dbContext.ChangeTracker.Entries())
{
// do any other stuff you want.
// ..
// ..
// work with ITrackable entities
var trackableObject = dbEntityEntry.Entity as ITrackable;
// we need to set/update trackable properties
if (trackableObject == null)
{
continue;
}
var dateTime = DateTime.Now;
// set createddate only for added entities
if (entityState.ObjectState == ObjectState.Added)
{
trackableObject.CreatedDate = dateTime;
}
// set LastUpdatedDate for any case other than Unchanged
if (entityState.ObjectState != ObjectState.Unchanged)
{
trackableObject.ModifiedDate = dateTime;
}
}
}
}
Now in your dbContext Save method for example you need to call this method to setup all these properties.
public override Task<int> SaveChangesAsync()
{
this.SyncObjectsStatePreCommit();
return base.SaveChangesAsync();
}
Hope that helps.