问题
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