If you want to override OnSave, you must override all save methods. In EF core 2.1, you can use the best solution with ChangeTracked and events. For instance:
You can create an interface or base class as shown below:
public interface IUpdateable
{
DateTime ModificationDate{ get; set; }
}
public class SampleEntry : IUpdateable
{
public int Id { get; set; }
public DateTime ModificationDate { get; set; }
}
Then, when creating the context, add the event to the change tracker:
context.ChangeTracker.StateChanged += context.ChangeTracker_StateChanged;
And the method:
private void ChangeTracker_StateChanged(object sender, Microsoft.EntityFrameworkCore.ChangeTracking.EntityStateChangedEventArgs e)
{
if(e.Entry.Entity is IUpdateable && e.Entry.State == EntityState.Modified)
{
var entry = ((IUpdateable)e.Entry.Entity);
entry.ModyficationDate = DateTime.Now;
}
}
It is simpler and you do not need to redefine all methods;
source
share