修改后的实体不会触发ObjectStateManagerChanged?

时间:2011-08-29 22:04:33

标签: c# entity-framework-4

以下是我在 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 ?或者我如何以其他方式实现类似功能?

1 个答案:

答案 0 :(得分:4)

因为只有ObjectStateManager在实体发生更改时才更改,才会触发此事件。这意味着仅当您从跟踪中附加,插入或删除实体时才会触发事件,但如果您更改已跟踪实体的状态则不会触发事件。它在MSDN中直接描述。

如果您想对实体中的更改做出反应,您必须自己实现它,例如在实体类型上实现INotifyPropertyChanged