Entity Framework, trigger mechanism for before update values

北战南征 提交于 2019-12-02 04:56:00

问题


Is there anyway in EF to have before update values of object?

e.g. When entity object let's say User is saved, i would like to know for logging purpose before update User object values.

Thanks,


回答1:


If you work with ObjectContext (edmx) you can subscribe to the SavingChanges event.

context.SavingChanges += context_SavingChanges;

This gives access to the original and current values when SaveChanges() is executed:

private void context_SavingChanges (object sender, EventArgs e)
{
    ObjectContext context = sender as ObjectContext;
    if (context != null)
    {
        foreach (ObjectStateEntry entry in context.ObjectStateManager
                                 .GetObjectStateEntries(EntityState.Modified))
        {
            // TODO: do some logging with these values.
            entry.OriginalValues;
            entry.CurrentValues;
        }
    }
}

If you work with DbContext you can get to the event by

((IObjectContextAdapter)this).ObjectContext.SavingChanges


来源:https://stackoverflow.com/questions/11231913/entity-framework-trigger-mechanism-for-before-update-values

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