如何有NHibernate的一个持续的String.Empty属性值NULL属性、String、NHibernate、NULL

2023-09-03 06:39:21 作者:我愿甘心垫底衬你的高贵。

我有,我想通过NHibernate的(W /流利的映射)保存到SQL Server的一个相当简单的类。该班由主要的可选字符串字段了。

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.

我的问题是我默认类领域的String.Empty避免NullRefExceptions当NHibernate的行保存到数据库中的每个列包含一个空字符串,而不是空。

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.

问:有没有办法,我让NHibernate的自动保存空当字符串属性为空字符串?或者,我需要我的垃圾code与IF(的String.Empty)检查?

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的是做什么你问它做的事。在一端,你说你尽量避免的NullReferenceException ,你要保存的另一端 NULL 的数据库时的值不为空。这听起来好像是一对矛盾。而不是试图解决此功能缺陷,试图以允许空值(和检查数据,以prevent的NRE的),或者不允许空值。

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 save NULL in 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.

如果有要覆盖NULL字段VS空字段,可以考虑读取正确的数据的特殊情况(不初始化为的String.Empty )。如果你对等于该数据库空值空字符串,只是初始化为空字符串的所有领域,以保持它的简单和一致的。

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.