How to create / update LastModified field in EF Code First

I want to add a column that stores the current DateTime when the record is saved to disk. What would be the best way to do this?

I know this is not a very difficult problem, but I wondered if there is any good practice or some EF function that will simplify the task. For example:

  • Is there a way to enable the logic for this field inside the Class table so that it automatically updates whenever it is saved to disk?
  • Is there any event to capture when the object is modified or saved?
+3
source share
2 answers

one option would be to create a repository layer and implement your own SaveChanges

public void SaveChanges() { foreach (var entry in Context.ChangeTracker.Entries<ICreatedAt>().Where(x => x.State == EntityState.Added && x.Entity.CreatedAt == default(DateTime))) entry.Entity.CreatedAt = DateTime.Now; foreach (var entry in Context.ChangeTracker.Entries<ICreatedBy>().Where(x => x.State == EntityState.Added && x.Entity.CreatedBy == null)) entry.Entity.CreatedBy = ContextManager.CurrentUser; foreach (var entry in Context.ChangeTracker.Entries<IModifiedAt>().Where(x => x.State == EntityState.Modified)) entry.Entity.ModifiedAt = DateTime.Now; foreach (var entry in Context.ChangeTracker.Entries<IModifiedBy>().Where(x => x.State == EntityState.Modified)) entry.Entity.ModifiedBy = ContextManager.CurrentUser; Context.SaveChanges(); } 
+2
source

Unfortunately, there are no events that you can subscribe to. My recommendation is to override the SaveChanges method in your context and make your own logic there (if you want to keep it clean, you can expose your own events)

EDIT

One of the solutions I chose for this was to allow all my objects to inherit from a common base class (e.g. EntityBase) that provides the BeforeSave () and AfterSave () methods that you can call in your custom DbContext when overriding the SaveChanges method (look at ChangeTracker for all changed records)

0
source

All Articles