NHibernate Mapping to System.Drawing.Color
nhibernate
Solution
Try this for size. An NHibernate user type doesn't replace the type you want to expose, it simply provides the mechanism for automatically mapping from the stored database type to the .NET type (here, from string to Color and vice versa).
public class ColorUserType : IUserType
{
public 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 == null ? typeof(Color).GetHashCode() + 473 : 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 colorString = (string)obj;
return ColorTranslator.FromHtml(colorString);
}
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 = ColorTranslator.ToHtml((Color)value);
}
}
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[] {new SqlType(DbType.StringFixedLength)}; }
}
public Type ReturnedType
{
get { return typeof(Color); }
}
public bool IsMutable
{
get { return true; }
}
}
The following mapping should then work:
<property
name="Color"
column="hex_color"
type="YourNamespace.ColorUserType, YourAssembly" />
For completeness, and thanks to Josh for this, if you're using FluentNHibernate, you can map it like this:
Map(m => m.Color).CustomTypeIs<ColorUserType>();
Problem
Is it possible to just do some sort of type conversion and map directly to System.Drawing.Color? I'm storing the colors as html/css values. i.e. #ffffff. I don't want to have to create a custom type that implements IUserType, that is just a wrapper for System.Drawing.Color.