0
我使用NHibernate 3和Microsoft SQL Server数据库(2005和更高版本)。 现在,我正在寻找一种方法来告诉NHibernate总是将NULL写入数据库而不是空字符串。 什么是最好的方法来做到这一点? - 或者是否有NHibernate中的开关可以做到这一点? 感谢您的帮助。NHibernate应该总是写NULL而不是空字符串
我使用NHibernate 3和Microsoft SQL Server数据库(2005和更高版本)。 现在,我正在寻找一种方法来告诉NHibernate总是将NULL写入数据库而不是空字符串。 什么是最好的方法来做到这一点? - 或者是否有NHibernate中的开关可以做到这一点? 感谢您的帮助。NHibernate应该总是写NULL而不是空字符串
您可以添加PreInsertEventListener并覆盖该函数,以将空字符串转换为空值。
去了解这个问题的方法是:
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;
}
}
,并在设置的SessionFactory确保你添加以下到您的配置
_config.ExposeConfiguration(
config => config.SetListener(ListenerType.PreInsert, new NhibernateEventListeners()));
希望这是你在找什么并帮助你。
检查http://stackoverflow.com/questions/2592556/how-to-have-nhibernate-persist-a-string-empty-property-value-as-null和也http://stackoverflow.com/questions/1187841/mapping-empty-strings-to-null-in-nhibernate – V4Vendetta 2012-03-22 08:37:55
嗨。感谢您的链接。我有一个问题:我已经看到,他们与Fluent合作。我使用hbm映射工作。这是否也适用于hbm映射? – BennoDual 2012-03-22 09:22:20
您也可以使用自定义IUserType与hbm映射。示例' ' –
Nikolay
2012-03-22 09:56:51