The simplest solution for this is at the database level:
- Create a new column in the table to save the
DateTime value. - Create a database trigger to set a column for each insert or update in the table.
- Match the new column as a property in your entity
- Set
StoreGeneratedPattern for the new Computed property so that the value generated in the database is correctly updated to your attached object after each insert or update.
If you do not like the trigger, you must do it manually to override SaveChanges, where you will find all the objects that will be inserted or updated, and set the column:
public override int SaveChanges(SaveOptions options) { var entities = ObjectStateManger.GetObjectStateEntries(EntityState.Added | EntityState.Modified) .Select(e => e.Entity) .OfType<YourEntityType>(); DateTime now = DateTime.Now; foreach(var entity in entities) { entity.Updated = now; } return base.SaveChanges(options); }
source share