2011-08-29 36 views
4

以下是我在MyObjectContext做類的構造函數:對於修改的實體,ObjectStateManagerChanged未被觸發?

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不被調用更新的實體?或者我如何以其他方式實現類似的功能?

回答

4

因爲只有在實體更改時ObjectStateManager更改,纔會觸發此事件。這意味着只有當你從追蹤中附加,插入或刪除實體時纔會觸發事件,但如果您更改已經追蹤的實體的狀態,則不會觸發事件。它在MSDN中直接描述。

如果你想對實體中的變化做出反應,你必須自己實現它,例如通過對實體類型實現INotifyPropertyChanged

+0

感謝您的澄清。 – Paul

+0

@Ladislav ...文檔做的狀態,但不是那麼明確......至少不是從那個鏈接...謝謝反正:-) – chosenbreed37