Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework EntityCollection Observing CollectionChanged

I'm using EntityFramework database first in an application. I would like somehow to be notified of changes to an EntityCollection in my ViewModel. It doesn't directly support INotifyCollectionChanged (why?) and I haven't been successful in finding another solution.

Here's my latest attempt, which doesn't work because the ListChanged event doesn't appear to get raised:

public class EntityCollectionObserver<T> : ObservableCollection<T>, INotifyCollectionChanged where T : class
{
    public event NotifyCollectionChangedEventHandler CollectionChanged;

    public EntityCollectionObserver(EntityCollection<T> entityCollection)
        : base(entityCollection)
    {
        IBindingList l = ((IBindingList)((IListSource)entityCollection).GetList());
        l.ListChanged += new ListChangedEventHandler(OnInnerListChanged);
    }

    private void OnInnerListChanged(object sender, ListChangedEventArgs e)
    {
        if (CollectionChanged != null) 
            CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
    }
}

Does anyone have any ideas how I might observe changes to an EntityCollection?

Dan

like image 640
djskinner Avatar asked Mar 31 '11 15:03

djskinner


1 Answers

have you tried handling AssociationChanged Occurs when a change is made to a related end. (Inherited from RelatedEnd.)

It gives arguments showing whether an element was added or deleted and also exposes the element.

like image 101
DermFrench Avatar answered Sep 17 '22 03:09

DermFrench