开发者

ObjectStateManagerChanged is not fired for modified entities?

Here is what I do in MyObjectContext class constructor:

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 开发者_如何学JAVAthe 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 after all 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 an event about updating the company entity. How do I ensure it does? The more interesting is that the company is included in the list of entities returned by:

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

which is called inside MyObjectContext.SaveChanges() method.

Does anybody know why ObjectStateManagerChanged isn't called for updated entities? Or how do I implement the similar functionality the other way?


Because this event is fired only if ObjectStateManager changes not if entity changes. That means that event is fired only when you attach, insert or remove entity from tracking but not if you change the state of already tracked entity. It is directly described in MSDN.

If you want to react on changes in entity you must implement it yourselves for example by implementing INotifyPropertyChanged on the entity type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜