I have a fairly simple class that I want to save to SQL Server via NHibernate (w/ Fluent mappings). The class is made up mostly of optional string fields.
My problem is I default the class fields to string.empty to avoid NullRefExceptions and when NHibernate saves the row to the database each column contains an empty string instead of null.
Question: Is there a way for me to get NHibernate to automatically save null when the string property is an empty string? Or do I need to litter my code with if (string.empty) checks?
NHibernate is doing what you ask it to do. At one end you are saying that you try to avoid
NullReferenceException, at the other end you are trying to saveNULLin the database when a value is not null. That sounds to me like a contradiction. Instead of trying to workaround this feature bug, try to either allow nulls (and check the data to prevent the NRE’s) or don’t allow nulls.If there’s a special case you want to cover with NULL fields vs empty fields, consider reading the correct data (and don’t init to
String.Empty). If you treat an empty string equal to a null value in that database, just initialize all fields to the empty string to keep it easy and consistent.