流畅的NHibernate插入Null FK

时间:2011-10-23 16:52:54

标签: nhibernate fluent-nhibernate

我有一个可以为空的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。我不知道如何实现这一目标。

1 个答案:

答案 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 } }
    }
}