我有一个相当简单的类,我想通过 NHibernate(带 Fluent 映射)将其保存到 SQL Server。该类主要由可选字符串字段组成。
我的问题是我将类字段默认为 string.empty 以避免 NullRefExceptions,并且当 NHibernate 将行保存到数据库时,每列包含一个空字符串而不是 null。
问题:有没有办法让NHibernate在string属性为空字符串时自动保存null?还是我需要用 if (string.empty) 检查乱丢代码?
最佳答案
您可以使用 UserType 执行此操作。我得出的结论是,空字符串在我的业务类中毫无用处(而且让人头疼),因此我将所有可为空的字符串数据库列转换为空字符串,反之亦然。
流利的用法是:
Map(x => x.MiddleName).CustomType(typeof(NullableString));
/// <summary>
/// UserType for string properties that are database nullable. Using this type
/// will substitue empty string for null when populating object properties
/// and null for empty string in database operations.
/// </summary>
/// <example>
/// Map(x => x.MiddleName).Length(30).Nullable().CustomType(typeof(NullableString));
/// </example>
public class NullableString : IUserType
{
public new bool Equals(object x, object y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (x == null || y == null)
{
return false;
}
return x.Equals(y);
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var valueToGet = NHibernateUtil.String.NullSafeGet(rs, names[0]);
return valueToGet ?? string.Empty;
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
var stringObject = value as string;
object valueToSet = string.IsNullOrEmpty(stringObject) ? null : stringObject;
NHibernateUtil.String.NullSafeSet(cmd, valueToSet, index);
}
public object DeepCopy(object value)
{
return value;
}
public object Replace(object original, object target, object owner)
{
return original;
}
public object Assemble(object cached, object owner)
{
return DeepCopy(cached);
}
public object Disassemble(object value)
{
return DeepCopy(value);
}
public SqlType[] SqlTypes
{
get
{
return new[] { new SqlType(DbType.String)};
}
}
public Type ReturnedType
{
get { return typeof(string); }
}
public bool IsMutable
{
get { return false; }
}
}
关于.net - 如何让 NHibernate 将 String.Empty 属性值保留为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2592556/