Skip to content

Instantly share code, notes, and snippets.

@Mark-Broadhurst
Created February 25, 2014 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mark-Broadhurst/9208462 to your computer and use it in GitHub Desktop.
Save Mark-Broadhurst/9208462 to your computer and use it in GitHub Desktop.
NHibernate Multi-Column DateType (When day month and year are in different columns)
#region Namespaces
using System;
using System.Data;
using NHibernate;
using NHibernate.SqlTypes;
using NHibernate.UserTypes;
#endregion
public class MultiColDateTime : IUserType
{
public SqlType[] SqlTypes
{
get
{
return new[]
{
NHibernateUtil.Int32.SqlType,
NHibernateUtil.Int32.SqlType,
NHibernateUtil.Int32.SqlType
};
}
}
public new bool Equals(object x, object y)
{
if (ReferenceEquals(x, y))
{
return true;
}
if (ReferenceEquals(null, x) || ReferenceEquals(null, y))
{
return false;
}
return x.Equals(y);
}
public int GetHashCode(object x)
{
return x == null ? typeof(DateTime).GetHashCode() + 473 : x.GetHashCode();
}
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 Type ReturnedType
{
get
{
return typeof(DateTime);
}
}
public bool IsMutable
{
get
{
return false;
}
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var day = (int)NHibernateUtil.Int32.NullSafeGet(rs, names[0]);
var month = (int)NHibernateUtil.Int32.NullSafeGet(rs, names[1]);
var year = (int)NHibernateUtil.Int32.NullSafeGet(rs, names[2]);
if (day == 0 || month == 0 || year == 0)
{
return null;
}
return new DateTime(year, month, day);
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
if (value == null)
{
((IDataParameter)cmd.Parameters[index]).Value = DBNull.Value;
}
else
{
var dateTime = (DateTime)value;
switch (index)
{
case 0:
((IDataParameter)cmd.Parameters[index]).Value = dateTime.Date;
break;
case 1:
((IDataParameter)cmd.Parameters[index]).Value = dateTime.Month;
break;
case 2:
((IDataParameter)cmd.Parameters[index]).Value = dateTime.Year;
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment