NHibernate按代码映射和IUsertype不起作用



我正在尝试通过代码获取使用 NHibernate (v3.3) 映射的自定义类型。我尝试在这里遵循此示例,但没有运气。我尝试实现的自定义类型是修剪来自数据库的字符串的类型。

我收到以下异常:

属性访问异常:无效强制转换(检查您的 属性类型不匹配的映射)。 {"无法将类型为'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 中。

Person中,它应该是...

public virtual string FirstName { get; set; }

...,不是TrimmedString. TrimmedString只是指示 NHibernate 您希望该属性如何水合和脱水的类。 应用它的属性应该是 ReturnedType 指定的类型 - 换句话说,String 。 NHibernate正在尝试使用string值设置FirstName属性(因为这是TrimmedString说它应该做的),但它不能,因为FirstName只允许TrimmedString s,因此"无效强制转换"错误。

最新更新