我查看了 Hibernate 社区并找到了使用IUserType
.
我创建了一个自定义类Bytes,它本质上是字节数组的序列化包装器:
[Serializable]
public class Bytes
{
private byte[] _value;
public byte[] Value { get { return _value; } }
public Bytes(byte[] bytesValue)
{
_value = bytesValue;
}
public override bool Equals(object obj) {...}
public override int GetHashCode() {...}
public override string ToString() {...}
}
字节用户类型:
public class BytesUserType : IUserType
{
private static readonly NHibernate.SqlTypes.SqlType[] _sqlTypes = { NHibernateUtil.Binary.SqlType };
public NHibernate.SqlTypes.SqlType[] SqlTypes { get { return _sqlTypes; } }
public Type ReturnedType { get { return typeof(Bytes); } }
public bool IsMutable { get { return false; } }
public object NullSafeGet(IDataReader dr, string[] names, object owner)
{
object obj = NHibernateUtil.Binary.NullSafeGet(dr, names[0]);
if (obj == null)
return null;
var value = (byte[])obj;
return new Bytes(value);
}
public void NullSafeSet(IDbCommand cmd, object obj, int index)
{
if (obj == null)
((IDataParameter)cmd.Parameters[index]).Value = DBNull.Value;
else
{
Bytes a = (Bytes)obj;
byte[] valueBytes = a.Value;
((IDataParameter)cmd.Parameters[index]).Value = valueBytes;
}
}
public new bool Equals(object x, object y) {...}
public object DeepCopy(object value) {...}
public int GetHashCode(object x) {...}
public object Replace(object original, object target, object owner) {...}
public object Assemble(object cached, object owner) {...}
public object Disassemble(object value) {...}
}
更新了我的实体和映射:
public class Product
{
public virtual Bytes Id { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
}
.
public ProductMapping()
{
Table("tblProduct");
Id(p => p.Id).Column("prdProductGuid").CustomType<BytesUserType>();
Map(p => p.Name).Column("prdName");
Map(p => p.Description).Column("prdDescription");
}
这就是诀窍!