Search code examples
nhibernateiusertype

NHibernate Map class name and resolve it with Reflection


I have a property of a class that is mapped to another class that can't be stored in the database and can't be serialized; it implements the state pattern. So I have something like this:

public IState MyState { get; set; }

Where I have two different states

public class LockedState : IState ...

public class UnlockedState : IState ...

In the database I need to persist the name of the current state that can be accomplished using, for example:

string name = myState.GetType().Name;

Do I have to write a custom and verbose IUserState or is there anything around?


Solution

  • In order to do that I had to implement a custom IUserType in the following way:

    public sealed class StateMapper : IUserType
    
    // get
    public object NullSafeGet(IDataReader rs, string[] names, object owner)
    {
    string objectName = (string)NHibernateUtil.String.NullSafeGet(rs, names[0]);
    Type stateType = Type.GetType(objectName, false, true);
    if (stateType == null)
    {
        return null;
    }
    // StateFacility is used by my code to create a new Type
    return StateFacility.CreateState(stateType);
    } 
    
    // set
    public void NullSafeSet(IDbCommand cmd, object value, int index)
    {
    if (value == null)
    {
        NHibernateUtil.String.NullSafeSet(cmd, null, index);
        return;
    }
      NHibernateUtil.String.NullSafeSet(cmd, value, index);
    }