Last active
January 3, 2020 06:05
-
-
Save xhafan/1b001bd9618d2c83a5839e356226739f to your computer and use it in GitHub Desktop.
NHibernate, Fluent.NHibernate and PostgreSql: How to map string property into PostgreSql json type using Fluent.NHibernate and IUserType
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SomeClassMappingOverrides : IAutoMappingOverride<SomeClass> | |
{ | |
public void Override(AutoMapping<SygicPoi> mapping) | |
{ | |
mapping.Map(x => x.Json).CustomSqlType("json").CustomType<StringAsJson>(); // Json property type is string | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// inspired by | |
// https://gist.github.com/bariloce/e65fe5db6c6ddf46e6f8 | |
// https://web.archive.org/web/20150214164507/http://blog.miraclespain.com/archive/2008/Mar-18.html | |
// https://nhibernate.info/blog/2009/10/15/mapping-different-types-iusertype.html | |
public class StringAsJson : IUserType | |
{ | |
bool IUserType.Equals(object x, object y) | |
{ | |
return string.Equals((string)x, (string)y); | |
} | |
public int GetHashCode(object x) | |
{ | |
return x == null ? 0 : x.GetHashCode(); | |
} | |
public object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session, object owner) | |
{ | |
var value = rs[names[0]]; | |
return value != DBNull.Value | |
? value | |
: null; | |
} | |
public void NullSafeSet(DbCommand cmd, object value, int index, ISessionImplementor session) | |
{ | |
var parameter = (NpgsqlParameter)cmd.Parameters[index]; | |
parameter.NpgsqlDbType = NpgsqlDbType.Json; | |
parameter.Value = value ?? DBNull.Value; | |
} | |
public object DeepCopy(object value) | |
{ | |
return value; | |
} | |
public object Replace(object original, object target, object owner) | |
{ | |
return original; | |
} | |
public object Assemble(object cached, object owner) | |
{ | |
return cached; | |
} | |
public object Disassemble(object value) | |
{ | |
return value; | |
} | |
public SqlType[] SqlTypes => new[] { new SqlType(DbType.String) }; | |
public Type ReturnedType => typeof(string); | |
public bool IsMutable => false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks:
https://gist.github.com/bariloce/e65fe5db6c6ddf46e6f8
https://web.archive.org/web/20150214164507/http://blog.miraclespain.com/archive/2008/Mar-18.html
https://nhibernate.info/blog/2009/10/15/mapping-different-types-iusertype.html