NHibernate ISession.Get() 在具有复合键的实体上抛出 InvalidCastException
本文关键字:实体 InvalidCastException 复合 Get ISession NHibernate | 更新日期: 2023-09-27 18:36:21
NHibernate的ISession的Get()方法在调用具有复合键的实体时会抛出InvalidCastException。
System.InvalidCastException : <>f__AnonymousType0`2[[System.Int16, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
我在 ISession.Get() 和组合键上的 NHibernate Documenatation 中看不到任何提示。然而,其他答案和博客文章建议我们可以用匿名类型作为id调用ISession.Get()。
起初,我认为这个问题仅适用于 VB.Net 因为它使用的匿名类型实现略有不同。因此,我用 C# 重写了测试用例,但没有再成功。我的代码有问题吗?
我的测试代码:
实体:
public class Composite1
{
// Test with composite key
public virtual short Key1 { get; set; }
public virtual string Key2 { get; set; }
public virtual string Text { get; set; }
public override bool Equals(object obj)
{
Composite1 o = obj as Composite1;
if (o==null) return false;
return o.Key1.Equals(this.Key1) && o.Key2.Equals(this.Key2);
}
public override int GetHashCode()
{
return Key1.GetHashCode() ^ Key2.GetHashCode();
}
}
映射:
class Composite1Map : ClassMap<Composite1>
{
public Composite1Map()
{
CompositeId().KeyProperty(x => x.Key1, "Key1")
.KeyProperty(x => x.Key2, "Key2");
Map(x => x.Text);
}
}
存储库中的 GetByID:
public Composite1 GetByID(short Key1, string Key2)
{
return Session.Get<Composite1>(new {Key1 = Key1, Key2 = Key2});
}
和失败的测试:
Composite1 composite1 = composite1Repository.GetByID(1, "Test");
在
另一个答案或您链接到的博客文章中都没有使用匿名类。他们所做的是使用对象初始值设定项语法来初始化实体类本身的对象。