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.
Asked
Active
Viewed 1,435 times
0
-
3check http://stackoverflow.com/questions/2592556/how-to-have-nhibernate-persist-a-string-empty-property-value-as-null and also http://stackoverflow.com/questions/1187841/mapping-empty-strings-to-null-in-nhibernate – V4Vendetta Mar 22 '12 at 08:37
-
Hi. Thanks for your links. I have a question: I have seen, that they work with Fluent. I work with hbm-mappings. Will this also work with hbm-mappings? – BennoDual Mar 22 '12 at 09:22
-
1You can use custom IUserType with hbm-mappings too. Example `
` – Nikolay Mar 22 '12 at 09:56
1 Answers
0
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.

Baz1nga
- 15,485
- 3
- 35
- 61