Search code examples
entity-framework-4wcf-ria-services

EF: Adding new item in a collection and notifying all other collections that new item is added


Lest say that we have several pages that retrieve items from the same EntitySet. If I add a new entity on one page, I need to add it to both EntitySet collection and myCollection:

Context.EntitySet.Add(item);
myCollection.Add(item);

What is the best way to notify other pages that new item is added (or deleted)? Editing an entity is no problem, since all pages get change notification without any problem.


Solution

  • Instead of binding to different instances of IEnumerable<T> myCollection, the recommended approach is to bind directly to Context.EntitySet<T>. EntitySet<T> implements INotifyCollectionChanged and INotifyPropertyChanged interfaces. When you bind to the same instance of EntitySet<T>, each page may be notified of changes by responding to the EntitySet<T>.CollectionChanged event. For example:

    // Page 1
    _myCollection = Context.EntitySet<MyItem>();
    _myCollection.CollectionChanged += MyItemsChanged;
    
    ...
    
    // Page 2
    _myCollection = Context.EntitySet<MyItem>();
    _myCollection.CollectionChanged += MyItemsChanged;
    

    When any page adds or removes from the collection, all pages are notified.

    In regards to your comment, IEnumerable<T> does not implement the INotifyCollectionChanged interface and does not publish any change notifications. The best results come from using the EntitySet<T> directly.