InvalidCastException - Cannot cast string to custom object even with
operators
I am probably trying to do something that isn't possible. I am working
with Castle.ActiveRecord / Nhibernate. I have been happy so far, but one
thing I have always wanted to able to so is have something like:
[Property(ColumnType = "StringClob")]
public IDictionary<string, string> MetaData { get; set; }
This, for obvious reasons. Isn't possible at the moment. I started playing
around with things to make this work and have come down to the following.
I have created a custom class that extends Dictionary
public class SerializableDictionary<TK, TV> : Dictionary<TK, TV>
{
public static explicit operator SerializableDictionary<TK,
TV>(System.String serialized)
{
return JsonConvert.DeserializeObject<SerializableDictionary<TK,
TV>>(serialized);
}
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
And in my ActiveRecord model I have this:
[Property(ColumnType = "StringClob")]
public SerializableDictionary<string, string> MetaData { get; set; }
This works extremely well when I save the data. It gets serialized nicely
and stores as a string. When I try to load a model though, I get the
following error:
Unable to cast object of type 'System.String' to type
'MyNamespace.SerializableDictionary`2[System.String,System.String]'.
I have looked ad deep as possible (using dotPeek) into where this is
happening. The stack trace led me to:
NHibernate.Bytecode.Lightweight.AccessOptimizer.SetPropertyValues(Object
target, Object[] values)
I am at a complete loss. I have scoured google to see if what I am trying
to do is even possible. Any help is much appreciated.