这是我在MyObjectContext类构造函数中的操作:
ObjectStateManager.ObjectStateManagerChanged += ObjectStateManagerObjectStateManagerChanged;
这里是处理程序:
private void ObjectStateManagerObjectStateManagerChanged(object sender, System.ComponentModel.CollectionChangeEventArgs e)
{
if (e.Element is MyClass)
{
var entity = e.Element as MyClass;
var state = ObjectStateManager.GetObjectStateEntry(e.Element).State;
if (e.Action == CollectionChangeAction.Add && state == EntityState.Added)
{
//this is working fine and all created entities 100% hit this point
}
//none of the below is ever resolves to true,
//and I need to be notified on each modified entity
if (e.Action == CollectionChangeAction.Add && state == EntityState.Modified)
{
}
else if (e.Action == CollectionChangeAction.Refresh && state == EntityState.Modified)
{
}
}
}
最后,进行以下测试:
var context = new MyObjectContext();
context.SetMergeOption(MergeOption.OverwriteChanges);
var company = new Company
{
Label = "Label",
};
context.Add(company);
context.SaveChanges();
company.Label = company.Label +" and so on";
context.Update(company);
context.SaveChanges();
它没有触发有关更新公司实体的事件。我该如何确保它能够触发?更有趣的是,公司包含在以下实体列表中:
IEnumerable<ObjectStateEntry> changedEntities =
ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
这个方法被称为在MyObjectContext.SaveChanges()
方法中调用。
有人知道为什么更新的实体没有调用ObjectStateManagerChanged吗?或者我如何实现类似的功能呢?