在NHibernate的使用中有可能遇到无法自动映射的类型,这个时候就需要自己定义类型了,NHibernate提供了IUserType来自定义新的类型。
如果某个字段需要处理,继承IUserType则可解决。(NHibernate可扩展性还是很强了)
示例:(文本中某字段为加密字段,展示需要解密,存储需要加密)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NHibernate.UserTypes; using NHibernate.SqlTypes; namespace Training.Models.Util { public class MyEnDeType : IUserType { private Type _type = typeof(string); #region IUserType 成员 public bool Equals(object x, object y) { return x == y; } public object Assemble(object cached, object owner) { return DeepCopy(cached); } public object DeepCopy(object value) { return value; } public object Disassemble(object value) { return DeepCopy(value); } public int GetHashCode(object x) { return x.ToString().GetHashCode(); } public bool IsMutable { get { return false; } } public object NullSafeGet(System.Data.IDataReader rs, string[] names, object owner) { object name = NHibernate.NHibernateUtil.String.NullSafeGet(rs, names[0]); if (name == null) return null; return new MEncry().SenMDecry(Convert.ToString(name), MEncry.encry_type.type2); } public void NullSafeSet(System.Data.IDbCommand cmd, object value, int index) { NHibernate.NHibernateUtil.String.NullSafeSet(cmd, new MEncry().SenMEncry(Convert.ToString(value), MEncry.encry_type.type2), index); } public object Replace(object original, object target, object owner) { return original; } public Type ReturnedType { get { return _type; } } public SqlType[] SqlTypes { get { return new SqlType[] { new SqlType(System.Data.DbType.String, 1) }; } } #endregion } }
重点在NullSafeSet和NullSafeGet方法,在这里要对数据类型进行处理。然后直接在xml中使用就行了。
<property column="name" type="Train.Utils.MyEnDeType,Train" name="Name" />
注:NullSafeGet 中的names[0] 为数据库中此字段的值。
NullSafeSet value为此字段的值。
备注:
<property name="name" formula="de_chines_str(name)" />
初始想法是想使用 formula 属性对字段进行计算,de_chines_str是数据库的函数(自定义函数),结果对字段进行修改时还需要执行另外一个数据库函数,使用formula不能满足要求,所以使用了IUserType自定义类型。
(使用formula属性,做update操作时字段不更新,暂时不清楚什么原因,可能是认为这个字段是公示计算结果,不是字段)