如何通过NHibernate将基于整数的值设置为null

3

我有一个能够为空的整数列,并将其映射到int属性。如何通过NHibernate将此值更改为null? int不能为null。

2个回答

5

使用可空类型 int? 替代 int,然后可以将其映射到数据库中的可空列。


NHibernate 知道这个吗?也就是说,它会正确地映射这个值吗? - Louis Rhys
没错,它可以轻松映射到可空的整型或任何可空的基元类型。 - Chris Kooken
当我使用type="double?"时,它会抛出运行时错误,因为显然它们无法解析类型。当我使用type="Nullable<Double>"时,它无法编译,因为我不能在XML属性内使用"<"。有什么建议吗? - Louis Rhys

0

你需要创建 Map(m => m.EmployeeId).CustomType(typeof(IntConvertToNullInt));

public class IntConvertToNullInt : IUserType { public SqlType[] SqlTypes { get { return new[] { SqlTypeFactory.Int32 }; } }

    public Type ReturnedType
    {
        get { return typeof(Int32); }
    }

    public bool IsMutable
    {
        get { return false; }
    }

    public int GetHashCode(object x)
    {
        if (x == null)
        {
            return 0;
        }
        return x.GetHashCode();
    }

    public object NullSafeGet(IDataReader rs, string[] names, object owner)
    {
        object obj = NHibernateUtil.Int32.NullSafeGet(rs, names[0]);
        if (obj == null)
        {
            return 0;
        }
        return Convert.ToInt32(obj);
    }

    public void NullSafeSet(IDbCommand cmd, object value, int index)
    {

        if (value == null)
        {
            NHibernateUtil.Int32.NullSafeSet(cmd, null, index);
            return;
        }
        else
        {
            int indexint = (int)value;
            if (indexint == 0)
            {
                NHibernateUtil.Int32.NullSafeSet(cmd, null, index);
            }
            else
            {
                NHibernateUtil.Int32.NullSafeSet(cmd, value, 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 cached;
    }

    public object Disassemble(object value)
    {
        return value;
    }

    bool IUserType.Equals(object x, object y)
    {
        return object.Equals(x, y);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接