61 lines
1.8 KiB
C#
61 lines
1.8 KiB
C#
using System;
|
|
|
|
namespace ln.bson.mapper.mappings
|
|
{
|
|
public class ArrayMapping<T> : BsonMapping
|
|
{
|
|
public ArrayMapping() : base(typeof(T[]))
|
|
{
|
|
}
|
|
|
|
public override bool TryMapValue(BsonMapper mapper, object o, out BsonValue bsonValue)
|
|
{
|
|
if (mapper.TryGetMapping(typeof(T), out BsonMapping elementMapping))
|
|
{
|
|
BsonArray bsonArray = new BsonArray();
|
|
T[] sourceArray = (T[])o;
|
|
|
|
foreach (T element in sourceArray)
|
|
{
|
|
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[] destinationArray = new T[bsonArray.Length];
|
|
|
|
for (int i = 0; i < destinationArray.Length; i++)
|
|
{
|
|
if (!elementMapping.TryMapValue(mapper, bsonArray[i], out object element))
|
|
{
|
|
o = null;
|
|
return false;
|
|
}
|
|
|
|
destinationArray[i] = (T)element;
|
|
}
|
|
|
|
o = destinationArray;
|
|
return true;
|
|
}
|
|
|
|
o = null;
|
|
return false;
|
|
}
|
|
}
|
|
} |