我有一个IPostLoadEventListener的实现,它将我们数据库中UTC的DateTime属性转换为用户的本地时区。
使用Session.Get处理NHibernate实体时这很好用,但我找不到让Linq for Nhibernate观察事件监听器的方法,这意味着任何实体上的DateTime属性都保留为UTC。
是否可以为Linq配置NHibernate以使用已在会话工厂中配置的事件侦听器?
答案 0 :(得分:2)
实现IUserType接口并改为使用它。以下是Date to Varchar
的示例public class DateToVarcharUserType : IUserType
{
public new bool Equals(object x, object y)
{
if (ReferenceEquals(x, y)) return true;
if (x == null || y == null) return false;
return x.Equals(y);
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var obj = NHibernateUtil.String.NullSafeGet(rs, names[0]);
if (obj == null) return null;
var value = (string)obj;
DateTime dateValue;
if (DateTime.TryParseExact(value, "MMddyyyy", null,DateTimeStyles.AssumeLocal, out dateValue))
{
return dateValue;
}
return null;
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
if (value == null)
{
((IDataParameter)cmd.Parameters[index]).Value = DBNull.Value;
}
else
{
var dateValue = (DateTime)value;
((IDataParameter)cmd.Parameters[index]).Value = dateValue.ToString("MMddyyyy");
}
}
public object DeepCopy(object value)
{
return value;
}
public object Replace(object original, object target, object owner)
{
return original;
}
public object Assemble(object cached, object owner)
{
return cached;
}
public object Disassemble(object value)
{
return value;
}
public SqlType[] SqlTypes
{
get { return new [] { NHibernateUtil.String.SqlType}; }
}
public Type ReturnedType
{
get { return typeof(DateTime); }
}
public bool IsMutable
{
get { return false; }
}
}