Search code examples
c#serializationfluent-nhibernatefluent-nhibernate-mapping

Storing an object[] as column in Fluent NHibernate


I have the following (partial) model:

class LogMessage{
    string Format;
    object[] args;
}

I want to store args[] as a single column in the table, taking advance of the fact that format arguments are generally serializable or can be converted to a string a priori.

I don't want to store the formatted message, I want to separately store format and args (this has several advantages).

How can I tell Fluent NHibernate to use a BLOB type to store that column and perform simple binary serialization/deserialization when persisting the entity?


Solution

  • Map(x => x.Args).CustomType<ObjectArrayType>();
    
    class ObjectArrayType : IUserType
    {
        public object NullSafeGet(IDBReader reader, string[] names, object owner)
        {
            byte[] bytes = NHibernateUtil.BinaryBlob.NullSafeGet(reader, names[0]);
            return Deserialize(bytes);
        }
    
        public void NullSafeSet(IDBCommand cmd, object value, int index)
        {
            var args = (object[])value;
            NHibernateUtil.BinaryBlob.NullSafeSet(cmd, Serialize(args), index);
        }
    
        public Type ReturnType
        {
            get { return typeof(object[]); }
        }
    
        public SqlType[] SqlTypes
        {
            get { return new [] { SqlTypeFactory.BinaryBlob } }
        }
    }