// // Licensed under the MIT License. See LICENSE file in the project root for full license information. // namespace MUnique.OpenMU.Persistence; using System.Collections; using System.Collections.Specialized; /// /// A collection adapter which adapts a to an , /// if inherits from . /// /// The type of the class. /// The type of the ef core. /// public class CollectionAdapter : ICollection, INotifyCollectionChanged where TEfCore : TClass { /// /// The raw collection which is the actually mapped collection by entity framework. /// private readonly ICollection _rawCollection; /// /// Initializes a new instance of the class. /// /// The raw collection which is the actually mapped collection by entity framework. public CollectionAdapter(ICollection rawCollection) { this._rawCollection = rawCollection; } /// public event NotifyCollectionChangedEventHandler? CollectionChanged; /// public int Count => this._rawCollection.Count; /// public bool IsReadOnly => this._rawCollection.IsReadOnly; /// public IEnumerator GetEnumerator() { return this._rawCollection.OfType().GetEnumerator(); } /// /// Returns an enumerator that iterates through a collection. /// /// /// An object that can be used to iterate through the collection. /// IEnumerator IEnumerable.GetEnumerator() { return this._rawCollection.GetEnumerator(); } /// public void Add(TClass item) { if (item is not TEfCore efCoreItem) { throw new ArgumentException($"The item needs to be of type {typeof(TEfCore)}.", nameof(item)); } this._rawCollection.Add(efCoreItem); this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new List { efCoreItem })); } /// public void Clear() { var items = this._rawCollection.ToList(); this._rawCollection.Clear(); this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, items)); } /// public bool Contains(TClass item) { if (item is not TEfCore efCoreItem) { return false; } return this._rawCollection.Contains(efCoreItem); } /// public void CopyTo(TClass[] array, int arrayIndex) { int i = 0; foreach (var item in this._rawCollection) { array[arrayIndex + i] = item; i++; } } /// public bool Remove(TClass item) { if (item is not TEfCore efCoreItem) { return false; } if (this._rawCollection.Remove(efCoreItem)) { this.CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, new List { efCoreItem })); return true; } return false; } }