I want to add a column that stores the current DateTime when a record is saved to disk. What would be the best way to accomplish this?
I know it's not a very complex problem, but I wondered if there is any best practice or any feature of EF that would simplify the task. For example:
one option would be to create 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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With