Linq for NHibernate Event Listener
I have an implementation of IPostLoadEventListener which converts DateTime properties from UTC in our database to the user's local time zone.
This works fine when working with NHibernate entities using Session.Get, but I can't find a way to get Linq for Nhibernate to observe the event listener, which means the DateTime properties on any entities are left at UTC.
Is it possible开发者_开发问答 to configure NHibernate for Linq to use the event listeners that have been configured in the session factory?
Implement IUserType interface and use that instead. Here is an example of 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; }
}
}
精彩评论