0

我想知道如果我想要一个在使用 EF Code First 时监听数据库中所做更改的事件,最好的方法是什么?

就像我有一个方法Update(),如果对数据库进行更改,比如向其中添加用户,就会引发该方法。

4

2 回答 2

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
                }
            }
    }
于 2012-09-24T20:29:33.683 回答
0

您对此有何看法 http://dotnet.dzone.com/articles/c-sqldependency-monitoring

于 2012-09-24T16:13:58.440 回答