[英]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? 我必须编写一个自定义且冗长的IUserState还是周围有东西?
In order to do that I had to implement a custom IUserType in the following way: 为此,我必须通过以下方式实现自定义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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.