0

I have a table mapping with nullable FK constraint. In my fluent mapping I am doing something like so:

public enum PlayerPosition
{
        None = 0,
        Forward = 1
//etc
}

Entity

public virtual PlayerPosition? Position { get; set; }

Map(x => x.Position).Column("PlayerPositionId").CustomType< PlayerPosition>();

What I would like to happen is when PlayerPosition is set to "None" Nhibernate will insert null. I am not sure how to make that happen.

2
  • 2
    So you want to have two representations of null, either PlayerPosition.None or an actual null value? Why? What does a stored null value mean in reverse, then, does it mean that the PlayerPosition property should be initialized to None or null? Seems like the simpler/cleaner solution would be to align your enum to what's actually in the database, and handle any oddball mappings in the mapping layer (that is, the mapping layer between NHibernate entities and domain or presentation model). I also don't actually see an FK (References) here - just a property mapping?
    – Aaronaught
    Oct 23, 2011 at 19:12
  • I am not adding it as a reference I am just mapping it. Yes I would like to map PlayerPosition.None to map to a null reference in the database. This is not a question about DB design or alignment it is a question about how to mapping a problem. Some things are out of my control.
    – Hunter D
    Oct 24, 2011 at 15:18

1 Answer 1

1

i would go for 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 } }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.