ln.objects/ng/mappings/DictionaryMapping.cs

85 lines
3.3 KiB
C#

using System;
using System.Linq;
using System.Collections;
using System.Reflection;
using System.Collections.Generic;
using ln.objects.catalog;
namespace ln.types.odb.ng.mappings
{
public class DictionaryMapping : IODBMapping
{
public DictionaryMapping()
{
}
public ODBEntity MapValue(Mapper mapper, object value)
{
Type dType = value.GetType();
if (dType.GetInterfaces().Contains(typeof(IDictionary)))
{
IDictionary dictionary = value as IDictionary;
Document document = new Document();
document["__asm__"] = new ODBStringValue(value.GetType().Assembly.GetName().Name);
document["__type__"] = new ODBStringValue(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];
ODBEntity okey = mapper.MapValue(key);
document[okey] = mapper.MapValue(v);
kTypes[okey] = new ODBStringValue(Mapper.GetTypeName(key?.GetType()));
vTypes[okey] = new ODBStringValue(Mapper.GetTypeName(v?.GetType()));
}
return document;
}
throw new NotImplementedException();
}
public object UnmapValue(Mapper mapper, ODBEntity oval)
{
Document document = oval as Document;
Type dType = Type.GetType(String.Format("{0}, {1}",document["__type__"].As<String>(),document["__asm__"].As<String>())); //;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 (ODBEntity key in document.Keys)
{
string skey = key.As<String>();
if (!skey.StartsWith("__", StringComparison.InvariantCulture) || !skey.EndsWith("__",StringComparison.InvariantCulture))
{
Type kt = ktypes.Contains(key) ? Type.GetType(ktypes[key].As<String>()) : kType;
Type vt = vtypes.Contains(key) ? Type.GetType(vtypes[key].As<String>()) : vType;
dictionary.Add(mapper.UnmapValue(kt, key), mapper.UnmapValue(vt, document[key]));
}
}
return dictionary;
}
}
throw new NotSupportedException();
}
}
}