2011-02-07 36 views
0

我有一個映射到另一個類的屬性,該類不能存儲在數據庫中,並且無法序列化;它實現了狀態模式。 所以我有這樣的事情:NHibernate映射類名並使用反射來解決它

public IState MyState { get; set; } 

在那裏我有兩種不同的狀態

public class LockedState : IState ... 

public class UnlockedState : IState ... 

在我需要堅持,可以使用,實現例如當前狀態的名稱數據庫:

string name = myState.GetType().Name; 

我是否必須編寫自定義和詳細的IUserState或有什麼附件?

回答

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); 
}