Friday, February 22, 2013

NHibernate: Unable to cast object of type 'System.Object' to type 'System.String'


I'm developing an application that uses NHibernate as data framework.

I've found a bug (I think so) in NHibernate that generates the following InvalidCastException when you try to save an istance of an entity.

[InvalidCastException] Unable to cast object of type 'System.Object' to type 'System.String'.
   at NHibernate.Type.AbstractStringType.ToString(Object val)
   at NHibernate.Type.NullableType.ToLoggableString(Object value, ISessionFactoryImplementor factory)
   at NHibernate.Impl.Printer.ToString(Object entity, EntityMode entityMode)
   at NHibernate.Impl.Printer.ToString(IEnumerator enumerator, EntityMode entityMode)
   at NHibernate.Event.Default.AbstractFlushingEventListener.FlushEverythingToExecutions(FlushEvent event)
   at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event)
   at NHibernate.Impl.SessionImpl.Flush()
   at Castle.Facilities.NHibernateIntegration.SessionDelegate.Flush()
...

I banged my head on this issue for hours and finally I've found a workaround.

NHibernate uses log4net as logging library, so in my log4net configuration I had the priority set to "DEBUG" in my <root> configuration:

    <root>
      <priority value="DEBUG" />
      <appender-ref ref="Default_Appender" />
    </root>

This issue occurs when NHibernate is trying to convert the instance to a "loggable string", and it does this operation when it needs to log.

So, I've set the priority to "INFO" level (as shown below) in order to avoid this type of conversion and it worked fine

    <root>
      <priority value="INFO" />
      <appender-ref ref="Default_Appender" />
    </root>


My NHibernate version is 3.2.0.4000 and log4net version is 1.2.10.0

If you are experiencing the same problem try this workaround and let me know if this work too.