通過在IsMutable
中返回false來使用戶類型不可變,並且僅在SetPropertyValue
中引發異常。
我有類似的東西,但有一個自己的數據類型而不是DateTimeOffset
。我只是爲你調整了代碼。它將日期存儲爲UTC時間,並將偏移量存儲爲TimeSpan
(存儲Ticks。當然,您不需要此分辨率,但是,您不應該存儲整個小時的時區,有時區偏移小時小數點! !是在一個開箱即用的作品。)
public class DateTimeOffsetUserType : ICompositeUserType
{
public bool IsMutable
{
get { return false; }
}
public void SetPropertyValue(object component, int property, object value)
{
throw new InvalidOperationException("Immutable, SetPropertyValue is not allowed");
}
public object NullSafeGet(System.Data.IDataReader dr, string[] names, NHibernate.Engine.ISessionImplementor session, object owner)
{
if (dr == null)
{
return null;
}
DateTime? utcTime;
TimeSpan? offset;
utcTime = (DateTime?)PropertyTypes[0].NullSafeGet(dr, names[0], session, owner);
offset = (TimeSpan?)PropertyTypes[1].NullSafeGet(dr, names[1], session, owner);
if (utcTime == null || offset == null) return null;
return new DateTimeOffset(utcTime.Value, offset.Value);
}
public void NullSafeSet(System.Data.IDbCommand cmd, object value, int index, NHibernate.Engine.ISessionImplementor session)
{
if (value == null)
{
NHibernateUtil.Timestamp.NullSafeSet(cmd, null, index);
NHibernateUtil.TimeSpan.NullSafeSet(cmd, null, index + 1);
}
else
{
DateTimeOffset dateTimeOffset = (DateTimeOffset)value;
PropertyTypes[0].NullSafeSet(cmd, dateTimeOffset.UtcDateTime, index, session);
PropertyTypes[1].NullSafeSet(cmd, dateTimeOffset.Offset, index + 1, session);
}
}
// other methods
好吧,公平的......我追隨到目前爲止。但是,你的'dt'實例如何回到域模型? – codekaizen 2009-07-27 17:49:31