How to make an integer-based value null via NHibernate
I have an INTEGER column that can be nul开发者_如何学Goled, and mapped it to an int property. How can I change this value to null via NHibernate? int can't be nulled.
use a nullable type int?
insead of int
and then you can map it to a nullable column in the database.
You have to create 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);
}
精彩评论