实体被修改后,ObjectStateManagerChanged事件没有被触发?

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个回答

4

因为此事件仅在 ObjectStateManager 改变时触发,而不是实体更改。这意味着事件仅在你将实体附加、插入或从跟踪中删除时才会触发,但如果你更改已跟踪的实体的状态,则不会触发该事件。这在MSDN中有明确说明。

如果您想对实体进行更改并做出反应,则必须自己实现,例如,在实体类型上实现 INotifyPropertyChanged 接口。


@Ladislav...文档确实有说明,但没有那么明确...至少从那个链接上看不出来...不管怎样,还是谢谢 :-) - chosenbreed37

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接