/// <summary>
        ///     Called by the <see cref="ObservableCollection{T}" /> base class when the collection changes.
        ///     This method looks at the change made to the collection and reflects those changes in the
        ///     state manager.
        /// </summary>
        /// <param name="e">
        ///     The <see cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs" /> instance containing the event data.
        /// </param>
        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            Debug.Assert(
                e.Action != NotifyCollectionChangedAction.Reset,
                "Should not get Reset event from our derived implementation of ObservableCollection.");

            // Avoid recursively reacting to changes made to this list while already processing state manager changes.
            // That is, the ObservableCollection only changed because we made a change based on the state manager.
            // We therefore don't want to try to repeat that change in the state manager.
            if (!_inStateManagerChanged &&
                _internalContext != null)
            {
                if (e.Action == NotifyCollectionChangedAction.Remove ||
                    e.Action == NotifyCollectionChangedAction.Replace)
                {
                    foreach (TEntity entity in e.OldItems)
                    {
                        _internalContext.Set <TEntity>().Remove(entity);
                    }
                }

                if (e.Action == NotifyCollectionChangedAction.Add ||
                    e.Action == NotifyCollectionChangedAction.Replace)
                {
                    foreach (TEntity entity in e.NewItems)
                    {
                        // For something that is already in the state manager as Unchanged or Modified we don't try
                        // to Add it again since doing so would change its state to Added, which is probably not what
                        // was wanted in this case.
                        if (!_internalContext.EntityInContextAndNotDeleted(entity))
                        {
                            _internalContext.Set <TEntity>().Add(entity);
                        }
                    }
                }
            }
            base.OnCollectionChanged(e);
        }