gpt4 book ai didi

c# - NHibernate 按代码映射和 IUsertype 不工作

转载 作者:太空宇宙 更新时间:2023-11-03 20:13:08 24 4
gpt4 key购买 nike

我正在尝试通过代码获取使用 NHibernate (v3.3) 映射的自定义类型。我试着按照这个例子 here ,但没有运气。我试图实现的自定义类型是一种修剪来自数据库的字符串的类型。

我收到以下异常:

PropertyAccessException: Invalid Cast (check your mapping for property type mismatches). {"Unable to cast object of type 'System.String' to type 'ConsoleApplication1.TrimmedString'."}

这是我的完整尝试(gist)。

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; }

...,不是 TrimmedStringTrimmedString 只是指示 NHibernate 您希望该属性如何被水合和脱水的类。它所应用的属性应该是 ReturnedType 指定的类型 - 换句话说,String。 NHibernate 试图用 string 值设置 FirstName 属性(因为那是 TrimmedString 说它应该做的),但它不能因为 FirstName 只允许 TrimmedString,因此出现“Invalid Cast”错误。

关于c# - NHibernate 按代码映射和 IUsertype 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18635390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com