gpt4 book ai didi

NHibernate:IUserType 不工作

转载 作者:行者123 更新时间:2023-12-04 15:01:12 27 4
gpt4 key购买 nike

我有这个实现 IUserType 的类:

public class StringToIntType : IUserType
{
/// <summary>
/// mutable object = an object whose state CAN be modified after it is created
/// </summary>
public bool IsMutable
{
get { return false; }
}

public Type ReturnedType
{
get { return typeof(StringToIntType); }
}

public SqlType[] SqlTypes
{
get { return new[] { NHibernateUtil.String.SqlType }; }
}

public object NullSafeGet(IDataReader rs, string[] names, object owner)
{
var obj = NHibernateUtil.String.NullSafeGet(rs, names[0]);

if (obj == null) return null;

var s = (string)obj;

int i;
if (Int32.TryParse(s, out i))
return i;
return -1;
}

public void NullSafeSet(IDbCommand cmd, object value, int index)
{
if (value == null)
{
((IDataParameter)cmd.Parameters[index]).Value = DBNull.Value;
}
else
{
var i = (int)value;
((IDataParameter)cmd.Parameters[index]).Value = i.ToString();
}
}

public object DeepCopy(object value)
{
return value;
}

public object Replace(object original, object target, object owner)
{
return original;
}

public object Assemble(object cached, object owner)
{
return cached;
}

public object Disassemble(object value)
{
return value;
}

public new bool Equals(object x, object y)
{
if (ReferenceEquals(x, y)) return true;

if (x == null || y == null) return false;

return x.Equals(y);
}

public int GetHashCode(object x)
{
return x == null ? typeof(int).GetHashCode() + 473 : x.GetHashCode();
}
}

我的映射:
public BarausLangMap()
{
Table("BARAUSLANG");

Id(x => x.ula).CustomType<StringToIntType>();

Map(x => x.bezeichnung);
Map(x => x.sprache);
Map(x => x.la);
Where("la = 'SPE'");
}

我的属性:
    public virtual int ula { get; set; }
public virtual String bezeichnung { get; set; }
public virtual Int32? sprache { get; set; }
public virtual String la { get; set; }

问题:当我做
var b = session.Get<BarausLang>(5);

它说
{NHibernate.TypeMismatchException: Provided id of the wrong type.
Expected: MobileServiceServer.Models.StringToIntType, got System.Int32

问题是什么?我认为 nHibernate 会隐式调用 StringToIntType 以将 int 转换为 string,反之亦然。我认为这就是重点。我以为 StringToIntType 仅用于映射?那我该怎么用呢?

最佳答案

你说得对,ReturnedType应该返回 NullSafeGet 将返回的类型。示例代码 you linked to不正确,ReturnedType应该返回 typeof(bool) .

此外,正确使用 Equals 方法非常重要,我建议对您的代码进行一些小的更改:

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

关于NHibernate:IUserType 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13956408/

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