NHibernate映射到System.Drawing.Color

Jos*_*ose 3 nhibernate

是否可以只进行某种类型转换并直接映射到System.Drawing.Color?我将颜色存储为html/css值.即#ffffff.我不想创建一个实现IUserType的自定义类型,它只是System.Drawing.Color的包装器.

Dav*_*d M 6

试试这个尺码.NHibernate用户类型不会替换您要公开的类型,它只是提供了从存储的数据库类型自动映射到.NET类型的机制(此处,从字符串到Color,反之亦然).

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后应该使用以下映射:

<property
    name="Color"
    column="hex_color"
    type="YourNamespace.ColorUserType, YourAssembly" />
Run Code Online (Sandbox Code Playgroud)

为了完整性,感谢Josh,如果你使用的是FluentNHibernate,你可以像这样映射它:

Map(m => m.Color).CustomTypeIs<ColorUserType>();
Run Code Online (Sandbox Code Playgroud)