ObjectStateManagerChanged not starting for modified objects?

Here is what I do in the constructor of the MyObjectContext class:

ObjectStateManager.ObjectStateManagerChanged += ObjectStateManagerObjectStateManagerChanged; 

and here is the handler:

 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) { } } } 

And finally do the following test:

  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(); 

It does not fire a company update event. How can i do this? The more interesting is the fact that the company is included in the list of objects returned:

  IEnumerable<ObjectStateEntry> changedEntities = ObjectStateManager.GetObjectStateEntries(EntityState.Modified); 

which is called inside the MyObjectContext.SaveChanges() method.

Does anyone know why ObjectStateManagerChanged is not called for updated objects? Or how to implement similar functionality in another way?

+4
source share
1 answer

Since this event is fired only if the ObjectStateManager does not change, if the entity changes. This means that the event is triggered only when you attach, insert or remove an object from tracking, but do not change the state of an already tracked object. It is directly described in MSDN .

If you want to respond to changes in an entity, you must implement it yourself, for example, by implementing INotifyPropertyChanged for an entity type.

+4
source

Source: https://habr.com/ru/post/1369574/


All Articles