How to set created date and Modified Date to enitites in DB first approach

LP13 picture LP13 · May 17, 2016 · Viewed 19.3k times · Source

In every SQL table in our application we have "CreatedDate" and "ModifiedDate" column. We are using DB first approach. When i save the data, i want these two column automatically populated. One approach is to have Default Value as getdate() on the SQL Table Column itself. So thats going to solve the problem partially. Meaning it will set the CreatedDate & ModifiedDate when entity is new. However when i am editing/updating the entity i want only ModifiedDate to be updated.
There are lot of articles doing it using Code first approach. But we are using DB first approach.
What are my options here?

Answer

kjppster picture kjppster · Aug 8, 2018

If you'd like to override OnSave you have to override all save methods.In EF core 2.1 you can use better solution with ChangeTracked and events. For example:

You can create interface or base class like example below:

public interface IUpdateable 
{ 
    DateTime ModificationDate{ get; set; }
}

public class SampleEntry : IUpdateable
{
    public int Id { get; set; }
    public DateTime ModificationDate { get; set; }
} 

Then on context creation add event to Change tracker:

context.ChangeTracker.StateChanged += context.ChangeTracker_StateChanged;

And 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.ModificationDate = DateTime.Now;
        }
    }

It's easier and you don't have to override all methods.