Lesser-Known NHibernate Features: Serializable Values

If you want to store anything in a property of an entity, you can declare it as Object or dynamic; as long as you set it to a value of a serializable type, as supported by BinaryFormatter, you’re good! You can even change the value afterwards to a different type, and it will be saved.

You map it like this, in mapping by code:

   1: ca.Property(x => x.Payload, x =>
   2: {
   3:     x.Column("`payload`");
   4:     x.NotNullable(false);
   5:     x.Type(NHibernateUtil.Serializable);
   6: });

Where the class should have a property of type Object or dynamic:

   1: //public virtual Object Payload
   2: public virtual dynamic Payload { get; set; }

NHibernate will return the same object type and all of its contents anytime you retrieve it.

Try that in other persistence frameworks! Winking smile



  • I've never heard of this feature :), You mentioned the binary formatter? Is it possible to serialize the value as xml instead? or perhaps json?

  • Hi, Tobias!
    It is, but not out of the box. It requires a custom user type. Why don't you try it? ;-)

  • Sorry, I meant JSON needs a custom user type, not XML. For XML you can store XmlDocuments or XDocuments, just use type NHibernateUtil.XmlDoc or NHibernateUtil.XDoc.

Add a Comment

As it will appear on the website

Not displayed

Your website