ln.types/odb/DictionaryMapping.cs

67 lines
2.1 KiB
C#

using System;
using ln.types.odb.values;
using System.Linq;
using System.Collections;
using System.Reflection;
using Castle.Components.DictionaryAdapter;
using System.Collections.Generic;
namespace ln.types.odb
{
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;
ODBDocument document = new ODBDocument();
document["__asm__"] = value.GetType().Assembly.GetName().Name;
document["__type__"] = value.GetType().FullName;
foreach (object key in dictionary.Keys)
{
object v = dictionary[key];
document[mapper.MapValue(key)] = mapper.MapValue(v);
}
return document;
}
throw new NotImplementedException();
}
public object UnmapValue(ODBMapper mapper, ODBValue oval)
{
ODBDocument document = oval.AsDocument;
Type dType = 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];
foreach (ODBValue key in document.Keys)
{
if (!key.Equals("__asm__") && !key.Equals("__type__"))
dictionary.Add(mapper.UnmapValue(kType, key), mapper.UnmapValue(vType, document[key]));
}
return dictionary;
}
}
throw new NotSupportedException();
}
}
}