有没有可能只进行某种类型转换并直接映射到System.Drawing.Color?我将颜色存储为html/css值。即#ffffff。我不想创建一个实现IUserType的自定义类型,它只是System.Drawing.Color的一个包装器。
发布于 2009-06-30 14:44:09
试试这个的大小。颜色用户类型不会替换您想要公开的类型,它只是提供了从存储的数据库类型自动映射到.NET类型的机制(在这里,从string到NHibernate,反之亦然)。
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; }
}
}然后,下面的映射应该会起作用:
<property
name="Color"
column="hex_color"
type="YourNamespace.ColorUserType, YourAssembly" />为了完整性,感谢Josh,如果你正在使用FluentNHibernate,你可以这样映射它:
Map(m => m.Color).CustomTypeIs<ColorUserType>();发布于 2009-06-30 14:35:19
我会花15分钟编写一个IUserType实现来直接转换颜色属性,这样您就不会有任何神奇的属性了。
请参阅http://www.lostechies.com/blogs/rhouston/archive/2008/03/23/mapping-strings-to-booleans-using-nhibernate-s-iusertype.aspx
这也有一个好处,你可以在HQL或Linq中使用你的颜色属性,这是你不能用魔术属性做的,尽管对于颜色这可能不是问题。
发布于 2009-06-30 14:22:11
我会这样做:
我将在我的类中创建一个私有字符串属性或字段,并将此属性/字段映射到用于在数据库中存储颜色的列。
然后,我将在我的类中创建一个公共属性,该属性返回一个Color,在该属性的getter中,我将存储在private字段/属性中的字符串转换为Color,在setter中,我将字符串字段/属性设置为与给定的Color值相对应的值。
public class MyEntity
{
private string htmlColorString;
public Color TheColor
{
get { return System.Drawing.ColorTranslator.FromHtml (htmlColorString); }
set
{
htmlColorString = System.Drawing.ColorTranslator.ToHtml(value);
}
}
}https://stackoverflow.com/questions/1063933
复制相似问题