Skip to content

Instantly share code, notes, and snippets.

@akunzai
Last active March 25, 2018 14:53
Show Gist options
  • Save akunzai/8899913 to your computer and use it in GitHub Desktop.
Save akunzai/8899913 to your computer and use it in GitHub Desktop.
NHibernate UnixTime UserType
using System;
using System.Data;
using NHibernate.SqlTypes;
using NHibernate.Util;
namespace NHibernate.UserTypes
{
public class UnixTimeType : IUserType
{
public System.Type ReturnedType => typeof(DateTimeOffset);
public SqlType[] SqlTypes => new[] { SqlTypeFactory.Int64 };
public object Assemble(object cached, object owner)
{
return cached;
}
public object DeepCopy(object value)
{
if (value == null) return null;
var date = (DateTimeOffset)value;
return new DateTimeOffset(date.Ticks, date.Offset);
}
public object Disassemble(object value)
{
return value;
}
public new bool Equals(object x, object y)
{
return EqualsHelper.Equals(x, y);
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
public bool IsMutable
{
get { return false; }
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var value = NHibernateUtil.Double.NullSafeGet(rs, names[0]);
var unitTime = Convert.ToInt64(value);
return DateTimeOffset.FromUnixTimeSeconds(unitTime);
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
if (value == null)
{
NHibernateUtil.Int64.NullSafeSet(cmd, null, index);
return;
}
var date = (DateTimeOffset)value;
var unixTime = date.ToUnixTimeSeconds();
NHibernateUtil.Int64.NullSafeSet(cmd, unixTime, index);
}
public object Replace(object original, object target, object owner)
{
return original;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment