How to make an integer null value through NHibernate

I have an INTEGER column that can be nullified and mapped to an int property. How to change this value to null via NHibernate? int cannot be undone.

+3
source share
2 answers

use the nullable int?insead type intand then you can map it to a nullable column in the database.

+5
source

You need to create a 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);
    }
0
source

All Articles