如何通过NHibernate使基于整数的值为null

时间:2011-05-10 02:17:21

标签: .net nhibernate null primitive-types sqldatatypes

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

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:0)

你必须创建Map(m => m.EmployeeId).CustomType(typeof(IntConvertToNullInt));

公共类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);
    }