Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create/update a LastModified field in EF Code First

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:

  • Is there any way to include the logic for this field inside the table Class, so that it's automatically updated whenever it's saved to disk?
  • Is there any event to capture when an object is modified or saved?
like image 397
salgiza Avatar asked Nov 18 '25 23:11

salgiza


1 Answers

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();
}
like image 150
maxlego Avatar answered Nov 20 '25 13:11

maxlego



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!