Skip to content

Instantly share code, notes, and snippets.

@JoshClose
Created November 15, 2011 15:44
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 JoshClose/1367376 to your computer and use it in GitHub Desktop.
Save JoshClose/1367376 to your computer and use it in GitHub Desktop.
NHibernate Mapping to System.Drawing.Color
public class ColorUserType : IUserType
{
public object Assemble( object cached, object owner )
{
return cached;
}
public object DeepCopy( object value )
{
return value;
}
public object Disassemble( object value )
{
return value;
}
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 == null ? typeof( Color ).GetHashCode() + 473 : x.GetHashCode();
}
public bool IsMutable
{
get
{
return true;
}
}
public object NullSafeGet( IDataReader rs, string[] names, object owner )
{
var obj = NHibernateUtil.String.NullSafeGet( rs, names[0] );
if( obj == null )
{
return null;
}
return ColorTranslator.FromHtml( (string)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 = ColorTranslator.ToHtml( (Color)value );
}
}
public object Replace( object original, object target, object owner )
{
return original;
}
public Type ReturnedType
{
get
{
return typeof( Color );
}
}
public SqlType[] SqlTypes
{
get
{
return new[] { new SqlType( DbType.StringFixedLength ) };
}
}
}
public class MyClass
{
public int Id { get; protected set; }
public Color FontColor { get; set; }
}
public class MyClassMap : ClassMap<MyClass>
{
public MyClassMap()
{
SetupMapping();
}
private void SetupMapping()
{
Id( m => m.Id );
Map( m => m.FontColor ).CustomTypeIs<ColorUserType>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment