我正在尝试通过代码获取与 NHibernate (v3.3) 映射一起使用的自定义类型。我尝试在此处遵循此示例,但没有运气。我试图实现的自定义类型是一种修剪来自数据库的字符串的类型。
我收到以下异常:
PropertyAccessException: Invalid Cast(检查您的映射是否有属性类型不匹配)。{“无法将“System.String”类型的对象转换为“ConsoleApplication1.TrimmedString”类型。”}
这是我的全部尝试(要点)。
public class TrimmedString : IUserType
{
public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
//treat for the posibility of null values
string resultString = (string) NHibernateUtil.String.NullSafeGet(rs, names[0]);
if (resultString != null)
return resultString.Trim();
return null;
}
public void NullSafeSet(IDbCommand cmd, object value, int index)
{
if (value == null)
{
NHibernateUtil.String.NullSafeSet(cmd, null, index);
return;
}
value = ((string) value).Trim();
NHibernateUtil.String.NullSafeSet(cmd, value, index);
}
public object DeepCopy(object value)
{
if (value == null) return null;
return string.Copy((String) value);
}
public object Replace(object original, object target, object owner)
{
return original;
}
public object Assemble(object cached, object owner)
{
return DeepCopy(cached);
}
public object Disassemble(object value)
{
return DeepCopy(value);
}
public SqlType[] SqlTypes
{
get
{
SqlType[] types = new SqlType[1];
types[0] = new SqlType(DbType.String);
return types;
}
}
public Type ReturnedType
{
get { return typeof (String); }
}
public bool IsMutable
{
get { return false; }
}
public new bool Equals(object x, object y)
{
if (ReferenceEquals(x, y)) return true;
var xString = x as string;
var yString = y as string;
if (xString == null || yString == null) return false;
return xString.Equals(yString);
}
public int GetHashCode(object x)
{
return x.GetHashCode();
}
}
这是我的映射:
public class Person
{
public virtual int Id { get; set; }
public virtual TrimmedString FirstName { get; set; }
public virtual string LastName { get; set; }
}
public class PersonMap : ClassMapping<Person>
{
public PersonMap()
{
Table("Source");
Id(i => i.Id);
Property(i => i.FirstName, map => map.Type<TrimmedString>());
Property(i => i.LastName);
}
}
不确定我是否必须在 NHibernate 配置对象中做任何特别的事情,但我已将其包含在上面链接的 Gist 中。