This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.
NHibernate supports the declaration of properties of user-defined types, that is, not entities, collections or primitive types. These are used for mapping a database columns, of any type, into a different type, which may not even be an entity; think, for example, of a custom user type that converts a BLOB column into an Image.
User types must implement interface NHibernate.UserTypes.IUserType. This interface specifies an Equals method that is used for comparing two instances of the user type. If this method returns false, the entity is marked as dirty, and, when the session is flushed, will trigger an UPDATE. So, in your custom user type, you must implement this carefully so that it is not mistakenly considered changed. For example, you can cache the original column value inside of it, and compare it with the one in the other instance.
Let’s see an example implementation of a custom user type that converts a Byte from a BLOB column into an Image:
In this case, we need to cache the original Byte data because it’s not easy to compare two Image instances, unless, of course, they are the same.