ln.types/odb/ng/mappings/DictionaryMapping.cs

85 lines
3.2 KiB
C#

using System;
using ln.types.odb.values;
using System.Linq;
using System.Collections;
using System.Reflection;
using System.Collections.Generic;
namespace ln.types.odb.ng.mappings
{
public class DictionaryMapping : IODBMapping
{
public DictionaryMapping()
{
}
public ODBValue MapValue(ODBMapper mapper, object value)
{
Type dType = value.GetType();
if (dType.GetInterfaces().Contains(typeof(IDictionary)))
{
IDictionary dictionary = value as IDictionary;
Document document = new Document();
document["__asm__"] = value.GetType().Assembly.GetName().Name;
document["__type__"] = value.GetType().FullName;
Document kTypes = new Document();
Document vTypes = new Document();
document["__ktypes__"] = kTypes;
document["__vtypes__"] = vTypes;
foreach (object key in dictionary.Keys)
{
object v = dictionary[key];
ODBValue okey = mapper.MapValue(key);
document[okey] = mapper.MapValue(v);
kTypes[okey] = ODBMapper.GetTypeName(key?.GetType());
vTypes[okey] = ODBMapper.GetTypeName(v?.GetType());
}
return document;
}
throw new NotImplementedException();
}
public object UnmapValue(ODBMapper mapper, ODBValue oval)
{
Document document = oval as Document;
Type dType = Type.GetType(String.Format("{0}, {1}",document["__type__"].AsString,document["__asm__"].AsString)); //;Assembly.Load(document["__asm__"].AsString).GetType(document["__type__"].AsString);
if (dType.IsGenericType)
{
IDictionary dictionary = (IDictionary)Activator.CreateInstance(dType, true);
if (dType.GetGenericTypeDefinition().Equals(typeof(Dictionary<,>)))
{
Type kType = dType.GetGenericArguments()[0];
Type vType = dType.GetGenericArguments()[1];
Document ktypes = document.Contains("__ktypes__") ? document["__ktypes__"] as Document : new Document();
Document vtypes = document.Contains("__vtypes__") ? document["__vtypes__"] as Document : new Document();
foreach (ODBValue key in document.Keys)
{
string skey = key.AsString;
if (!skey.StartsWith("__", StringComparison.InvariantCulture) || !skey.EndsWith("__",StringComparison.InvariantCulture))
{
Type kt = ktypes.Contains(key) ? Type.GetType(ktypes[key].AsString) : kType;
Type vt = vtypes.Contains(key) ? Type.GetType(vtypes[key].AsString) : vType;
dictionary.Add(mapper.UnmapValue(kt, key), mapper.UnmapValue(vt, document[key]));
}
}
return dictionary;
}
}
throw new NotSupportedException();
}
}
}