Skip to content

Instantly share code, notes, and snippets.

@Mark-Broadhurst
Created February 25, 2014 13:14
Show Gist options
  • Save Mark-Broadhurst/9208500 to your computer and use it in GitHub Desktop.
Save Mark-Broadhurst/9208500 to your computer and use it in GitHub Desktop.
NHibernate StringToEnum abstract class (Allows you to store an enum as a string)
#region Namespaces
using System;
using System.Data;
using NHibernate;
using NHibernate.SqlTypes;
using NHibernate.UserTypes;
#endregion
public abstract class StringToEnum<T> : IUserType
where T : struct, IConvertible
{
protected StringToEnum()
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
}
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(T).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 SqlType[] SqlTypes
{
get
{
return new[] { NHibernateUtil.String.SqlType };
}
}
public Type ReturnedType
{
get
{
return typeof(T);
}
}
public bool IsMutable
{
get
{
return false;
}
}
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var obj = (string)NHibernateUtil.String.NullSafeGet(rs, names[0]);
if (obj == null)
{
return null;
}
return ParseTo(obj);
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
if (value == null)
{
((IDataParameter)cmd.Parameters[index]).Value = DBNull.Value;
}
else
{
((IDataParameter)cmd.Parameters[index]).Value = ParseFrom((T)value);
}
}
protected abstract T ParseTo(string s);
protected abstract string ParseFrom(T s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment