1

I'm using entity framework 6 with change tracking and lazy loading enabled, all the properties are virtual to improve change tracking performance (by using self tracking entities), so by default EF creates an EntityCollection<TEntity> to contain navigation properties lists of entities.

The thing is however that EntityCollection doesn't implement INotifyCollectionChanged, so I can't add a handler to the CollectionChanged event, which is what I'd like to achieve.

In detail, I'd like to change another property when the collection is changed (i.e. an item is added or removed).

The navigation properties are defined as an ICollection<TEntity>, which I don't initialize to a value (EF takes care of it by itself by creating a new EntityCollection<TEntity>, if I try to instantiate the navigation property as an ObservableCollection<TEntity> for example, I get an error).

I also tried to create an extension of EntityCollection<TEntity> like:

public class ObservableEntityCollection<TEntity> : EntityCollection<TEntity>,  INotifyCollectionChanged where TEntity : class { ... }

and overriding the Add, Remove and Clear methods like this:

public override void Add(TEntity item)
   {
       base.Add(item);
       OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item));
   }

However the aforementioned methods are not virtual, so I can't really override them (nor hiding them, I don't believe it would work).

I am also aware that using POCO objects for the model in the mvvm pattern isn't the best solution, but that's not the scope of the question.

Thanks in advance for your help.

Filippo Vigani
  • 904
  • 1
  • 9
  • 22
  • You can change the collection type of navigation properties to a supported type also implementing an ICollection from scratch. EF will create the right collection during load and you can observe the collection the way you like. – bubi Sep 14 '16 at 15:30
  • @bubi So you're suggesting to change ICollection to ObservableCollection on all the navigation properties definitions? EDIT: If I do as such, i lost the benefit of self tracking properties: the DetectChanges method checks for all the entities instead of storing changes on the proxies. – Filippo Vigani Sep 14 '16 at 15:39

0 Answers0