我想知道如果我想要一个能够在使用EF Code First时监听数据库中所做更改的事件,那么最好的方法是什么?
就像我有一个方法Update()
,如果对数据库进行更改就会引发它,就像添加用户一样。
答案 0 :(得分:0)
public MyContext() {
((IObjectContextAdapter)this).ObjectContext.SavingChanges += SavingChangesHandler;
}
private void SavingChangesHandler(object sender, EventArgs e) {
foreach (DbEntityEntry entry in ChangeTracker.Entries().Where(entry => entry.State == EntityState.Added || entry.State == EntityState.Modified || entry.State == EntityState.Deleted)) {
_log.DebugFormat("{0} Entity: {1}", entry.State.ToString(), entry.Entity.ToString().Contains("DynamicProxies") ? entry.Entity.GetType().BaseType.Name : entry.Entity.ToString());
if (entry.State != EntityState.Deleted) {
var changedProperties = entry.CurrentValues.PropertyNames.Where(p => entry.Property(p).IsModified);
changedProperties.ToList().ForEach(p => _log.DebugFormat("{0} changed from {1} to {2}", p, entry.Property(p).OriginalValue, entry.Property(p).CurrentValue));
//TODO: handle complex properties
}
}
}