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.