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

假装没事ソ 提交于 2019-12-23 18:45:07

问题


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?

回答1:


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();
}



回答2:


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

EDIT

One solution i picked for this was to let all my entities inherit from a common base class (e.g. EntityBase) which exposes the methods BeforeSave() and AfterSave() which you can call in your custom DbContext when overriding the SaveChanges method ( look at the ChangeTracker for all modified entries )



来源:https://stackoverflow.com/questions/6029766/how-to-create-update-a-lastmodified-field-in-ef-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!