ln.bson/ln.bson/mapper/mappings/ListMapping.cs

63 lines
1.8 KiB
C#

using System;
using System.Collections.Generic;
namespace ln.bson.mapper.mappings
{
public class IListMapping<T, E> : BsonMapping where T : IList<E>
{
public IListMapping() : base(typeof(T))
{
}
public override bool TryMapValue(BsonMapper mapper, object o, out BsonValue bsonValue)
{
if (mapper.TryGetMapping(typeof(E), out BsonMapping elementMapping))
{
BsonArray bsonArray = new BsonArray();
T source = (T)o;
foreach (E element in source)
{
if (!elementMapping.TryMapValue(mapper, element, out BsonValue elementValue))
{
bsonValue = null;
return false;
}
bsonArray.Add(elementValue);
}
bsonValue = bsonArray;
return true;
}
bsonValue = null;
return false;
}
public override bool TryMapValue(BsonMapper mapper, BsonValue bsonValue, out object o)
{
if (bsonValue is BsonArray bsonArray && mapper.TryGetMapping(typeof(T), out BsonMapping elementMapping))
{
T destinationList = Activator.CreateInstance<T>();
for (int i = 0; i < bsonArray.Length; i++)
{
if (!elementMapping.TryMapValue(mapper, bsonArray[i], out object element))
{
o = null;
return false;
}
destinationList.Add((E)element);
}
o = destinationList;
return true;
}
o = null;
return false;
}
}
}