//
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace MUnique.OpenMU.Persistence.EntityFramework;
using System.Collections;
///
/// A many-to-many collection adapter which adapts beween and .
///
///
/// Usually in our object model we don't define collections of join entities and their types.
/// This is done automatically by our T4 templates.
///
/// The type which is in a many to many relationship.
/// The type of the join entity. It contains a property of .
///
internal class ManyToManyCollectionAdapter : ICollection
{
///
/// The raw collection, which is usually the collection which is mapped by entity framework.
///
private readonly ICollection _rawCollection;
///
/// The function to create a new join entity.
///
private readonly Func _createJoinEntityFunction;
///
/// The function to extract the instance of out of .
///
private readonly Func _extractFunction;
///
/// Initializes a new instance of the class.
///
/// The raw collection, which is usually the collection which is mapped by entity framework.
/// The function to extract the instance of out of .
/// The function to create a new join entity.
public ManyToManyCollectionAdapter(ICollection rawCollection, Func extractFunction, Func createJoinEntityFunction)
{
this._rawCollection = rawCollection;
this._createJoinEntityFunction = createJoinEntityFunction;
this._extractFunction = extractFunction;
}
///
public int Count => this._rawCollection.Count;
///
public bool IsReadOnly => this._rawCollection.IsReadOnly;
///
public IEnumerator GetEnumerator()
{
return this._rawCollection.Select(this._extractFunction).GetEnumerator();
}
///
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
///
public void Add(T item)
{
if (item != null)
{
this._rawCollection.Add(this._createJoinEntityFunction(item));
}
}
///
public void Clear()
{
this._rawCollection.Clear();
}
///
public bool Contains(T item)
{
return this._rawCollection.Any(i => object.Equals(this._extractFunction(i), item));
}
///
public void CopyTo(T[] array, int arrayIndex)
{
this._rawCollection.Select(this._extractFunction).ToList().CopyTo(array, arrayIndex);
}
///
public bool Remove(T item)
{
var joinItem = this._rawCollection.FirstOrDefault(i => object.Equals(this._extractFunction(i), item));
if (joinItem != null)
{
return this._rawCollection.Remove(joinItem);
}
return false;
}
}