.net - 如何让 NHibernate 将 String.Empty 属性值保留为 NULL

标签 .net nhibernate fluent-nhibernate

我有一个相当简单的类,我想通过 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/

相关文章:

nhibernate - 休眠。将 HQL 转换为 Criteria API

.net - 如何转义冒号 ( :) character while executing native SQL queries against an Informix database using NHibernate?

c# - C#中的自动类型转换

c# - Windows Vista\7 上的应用程序 list 、管理员权限和自动启动

c# - NHibernate 二级缓存与 NHibernate Linq Provider 1.0

c# - 如果我使用类似 NHibernate 的 ORM,为什么还需要 LINQ?

fluent-nhibernate - 流畅的 NHibernate 和计算属性

c# - NHibernate.LazyInitializationException 异常

C# 递归方法返回空引用,对象引用未设置为对象的实例。 XElement 对象

.net - 如何在 Visual Studio Team Services 中发布和访问 nuget 包