我有一个可以为空的FK约束的表映射。在我的流利映射中,我正在做这样的事情:
public enum PlayerPosition
{
None = 0,
Forward = 1
//etc
}
实体
public virtual PlayerPosition? Position { get; set; }
Map(x => x.Position).Column("PlayerPositionId").CustomType< PlayerPosition>();
我想要发生的是当PlayerPosition设置为“None”时Nhibernate将插入null。我不知道如何实现这一目标。
答案 0 :(得分:1)
我会选择IUserType:
public virtual PlayerPosition Position { get; set; }
Map(x => x.Position).Column("PlayerPositionId").CustomType<PlayerPositionUserType>();
class PlayerPositionUserType : IUserType
{
public object NullSafeGet(IDBReader reader, string[] names, object owner)
{
int? positionvalue = NHibernateUtil.Int32.NullSafeGet(reader, names[0]);
return (positionvalue.HasValue) ? (PlayerPosition)positionvalue : PlayerPosition.None;
}
public void NullSafeSet(IDBCommand cmd, object value, int index)
{
var position = (PlayerPosition)value;
if (position == PlayerPosition.None)
NHibernateUtil.Int32.NullSafeSet(cmd, null, index);
else
NHibernateUtil.Int32.NullSafeSet(cmd, (int)position, index);
}
public Type ReturnType
{
get { return typeof(PlayerPosition); }
}
public SqlType[] SqlTypes
{
get { return new [] { SqlTypeFactory.Int32 } }
}
}