Search code examples
c#sql-servernhibernatenhibernate-3

NHibernate should always write NULL instead of empty string


I use NHibernate 3 with Microsoft SQL Server Database (2005 and higher). Now, I am searching a way to tell NHibernate to write always NULL to the database instead of empty strings. What would be the best way to do this? - Or is there perhaps a switch in NHibernate to do this? Thanks for your help.


Solution

  • You can add a PreInsertEventListener and override the function to do the necessary conversion of an empty string to a NULL value.

    The way to go about this would be:

     public class NhibernateEventListeners :  IPreInsertEventListener
        {
             public bool OnPreInsert(PreInsertEvent nHibernateEvent)
            {
                var entityBeingInserted = nHibernateEvent.Entity;
                if (entityBeingInserted == null)
                    return false;
                 if (property.PropertyType==typeof(string))
                     {
                        //use reflection to set the property value to null   
                     }
                return false;
            }
       }
    

    and while setting up the sessionfactory make sure you add the following to your configuration

    _config.ExposeConfiguration(
                            config => config.SetListener(ListenerType.PreInsert, new NhibernateEventListeners()));
    

    Hope this is what you are looking for and helps you.