65 lines
2.5 KiB
C#
65 lines
2.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Reflection;
|
|
|
|
namespace ln.bson.mapper.mappings
|
|
{
|
|
public class ClassStructMapping<T> : BsonMapping
|
|
{
|
|
private FieldInfo[] mappedFields;
|
|
//private PropertyInfo[] mappedProperties;
|
|
|
|
public ClassStructMapping() : base(typeof(T))
|
|
{
|
|
mappedFields = typeof(T).GetFields(BindingFlags.Instance | BindingFlags.Public |
|
|
BindingFlags.NonPublic);
|
|
}
|
|
|
|
public override bool TryMapValue(BsonMapper mapper, object o, out BsonValue bsonValue)
|
|
{
|
|
BsonDocument bsonDocument = new BsonDocument();
|
|
foreach (FieldInfo fieldInfo in mappedFields)
|
|
{
|
|
object fieldValue = fieldInfo.GetValue(o);
|
|
if (fieldValue is null)
|
|
bsonDocument.Add(fieldInfo.Name, BsonNull.Instance);
|
|
else if (mapper.TryGetMapping(fieldInfo.FieldType, out BsonMapping fieldMapping) &&
|
|
fieldMapping.TryMapValue(mapper, fieldValue, out BsonValue bsonElementValue))
|
|
bsonDocument.Add(fieldInfo.Name, bsonElementValue);
|
|
}
|
|
|
|
bsonValue = bsonDocument;
|
|
return true;
|
|
}
|
|
|
|
public override bool TryMapValue(BsonMapper mapper, BsonValue bsonValue, out object o)
|
|
{
|
|
o = Activator.CreateInstance(SourceType, true);
|
|
|
|
if (bsonValue is BsonDocument bsonDocument)
|
|
{
|
|
foreach (FieldInfo fieldInfo in mappedFields)
|
|
{
|
|
if (bsonDocument.Contains(fieldInfo.Name))
|
|
{
|
|
object fieldValue;
|
|
BsonValue bsonFieldValue = bsonDocument[fieldInfo.Name];
|
|
|
|
if (bsonFieldValue is BsonNull)
|
|
fieldValue = null;
|
|
else if (mapper.TryGetMapping(fieldInfo.FieldType, out BsonMapping fieldMapping) &&
|
|
fieldMapping.TryMapValue(mapper, bsonDocument[fieldInfo.Name], out fieldValue))
|
|
{ }
|
|
else
|
|
{
|
|
o = null;
|
|
return false;
|
|
}
|
|
fieldInfo.SetValue(o, fieldValue);
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
}
|
|
} |