Skip to content

Instantly share code, notes, and snippets.

@FSou1 FSou1/JsonMappableType.cs
Last active Feb 22, 2017

Embed
What would you like to do?
// Implementation of custom NHibernate type, that helps to store and retrive JSON format
// JsonFormatter - static class with Serialize/Deserialize methods (with JsonConvert implementation for example)
namespace Tm.NHibernate.Types
{
public class JsonMappableType<T> : IUserType where T : class
{
public new bool Equals(object x, object y)
{
if (x == null && y == null)
return true;
if (x == null || y == null)
return false;
return JsonFormatter.Serialize(x) == JsonFormatter.Serialize(y);
}
public int GetHashCode(object x)
{
if (x == null)
return 0;
return x.GetHashCode();
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
if(names.Length != 1)
throw new InvalidOperationException("Expect only one column");
var val = rs[names[0]] as string;
if (!string.IsNullOrWhiteSpace(val))
{
return JsonFormatter.Deserialize<T>(val);
}
return null;
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
var parameter = (DbParameter) cmd.Parameters[index];
parameter.Value = value == null
? (object) DBNull.Value
: JsonFormatter.Serialize(value);
}
public object DeepCopy(object value)
{
if (value == null)
return null;
var serialized = JsonFormatter.Serialize(value);
return JsonFormatter.Deserialize<T>(serialized);
}
public object Replace(object original, object target, object owner)
{
return original;
}
public object Assemble(object cached, object owner)
{
var str = cached as string;
if (string.IsNullOrWhiteSpace(str))
return null;
return JsonFormatter.Deserialize<T>(str);
}
public object Disassemble(object value)
{
if (value == null)
return null;
return JsonFormatter.Serialize(value);
}
public SqlType[] SqlTypes
=> new SqlType[] {new StringClobSqlType() };
public Type ReturnedType
=> typeof(T);
public bool IsMutable
=> true;
}
}
// Usage example
public class Scenario {
public virtual ISet<Call> Calls { get; set; }
}
public class ScenarioMap {
public ScenarioMap() {
Map(x => x.Calls).CustomType<JsonMappableType<ISet<Call>>>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.