实体框架,更新前值的触发机制 [英] Entity Framework, trigger mechanism for before update values

查看:83
本文介绍了实体框架,更新前值的触发机制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在更新对象的值之前,EF中仍然有吗?

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.

谢谢

推荐答案

如果使用ObjectContext(edmx),则可以订阅

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

context.SavingChanges += context_SavingChanges;

这可以在执行SaveChanges()时访问原始值和当前值:

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

如果您使用DbContext,则可以通过以下方式进入活动

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

((IObjectContextAdapter)this).ObjectContext.SavingChanges

这篇关于实体框架,更新前值的触发机制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆