0

我有一个类的属性,该属性映射到另一个无法存储在数据库中且无法序列化的类;它实现了状态模式。所以我有这样的事情:

public IState MyState { get; set; }

我有两种不同的状态

public class LockedState : IState ...

public class UnlockedState : IState ...

在数据库中,我需要保留可以使用的当前状态的名称,例如:

string name = myState.GetType().Name;

我是否必须编写自定义和详细的 IUserState 或者周围有什么?

4

1 回答 1

0

为了做到这一点,我必须通过以下方式实现自定义 IUserType:

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);
}
于 2011-02-07T17:23:02.703 回答