Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ObjectStateManagerChanged是否未为修改的实体激发?_C#_Entity Framework 4 - Fatal编程技术网

C# ObjectStateManagerChanged是否未为修改的实体激发?

C# ObjectStateManagerChanged是否未为修改的实体激发?,c#,entity-framework-4,C#,Entity Framework 4,以下是我在MyObjectContext类构造函数中所做的操作: ObjectStateManager.ObjectStateManagerChanged += ObjectStateManagerObjectStateManagerChanged; 这是处理程序: private void ObjectStateManagerObjectStateManagerChanged(object sender, System.ComponentModel.CollectionChangeEvent

以下是我在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);
IEnumerable changedEntities=
ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
它在
MyObjectContext.SaveChanges()方法中调用


有人知道为什么不为更新的实体调用ObjectStateManagerChanged?或者如何以另一种方式实现类似的功能?

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


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

@Ladislav…文档确实说明了这一点,但不是很明确…至少不是通过该链接实现的…无论如何,谢谢:-)