62 lines
2.0 KiB
C#
62 lines
2.0 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text.Json;
|
|
|
|
namespace ln.bson.mapper.mappings
|
|
{
|
|
public class DictionaryMapping<T> : BsonMapping
|
|
{
|
|
public DictionaryMapping() : base(typeof(Dictionary<string,T>))
|
|
{
|
|
}
|
|
|
|
public override bool TryMapValue(BsonMapper mapper, object o, out BsonValue bsonValue)
|
|
{
|
|
if (mapper.TryGetMapping(typeof(T), out BsonMapping elementMapping))
|
|
{
|
|
Dictionary<string, T> d = (Dictionary<string, T>)o;
|
|
BsonDocument bsonDocument = new BsonDocument();
|
|
|
|
foreach (KeyValuePair<string, T> keyValuePair in d)
|
|
{
|
|
if (!elementMapping.TryMapValue(mapper, keyValuePair.Value, out BsonValue elementValue))
|
|
{
|
|
bsonValue = null;
|
|
return false;
|
|
}
|
|
bsonDocument.Add(keyValuePair.Key, elementValue);
|
|
}
|
|
|
|
bsonValue = bsonDocument;
|
|
return true;
|
|
}
|
|
bsonValue = null;
|
|
return false;
|
|
|
|
}
|
|
|
|
public override bool TryMapValue(BsonMapper mapper, BsonValue bsonValue, out object o)
|
|
{
|
|
if (bsonValue is BsonDocument bsonDocument && mapper.TryGetMapping(typeof(T), out BsonMapping elementMapping))
|
|
{
|
|
Dictionary<string, T> d = new Dictionary<string, T>();
|
|
|
|
foreach (KeyValuePair<string,BsonValue> keyValuePair in bsonDocument)
|
|
{
|
|
if (!elementMapping.TryMapValue(mapper, keyValuePair.Value, out object element))
|
|
{
|
|
o = null;
|
|
return false;
|
|
}
|
|
d.Add(keyValuePair.Key, (T)element);
|
|
}
|
|
|
|
o = d;
|
|
return true;
|
|
}
|
|
|
|
o = null;
|
|
return false;
|
|
}
|
|
}
|
|
} |