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