【问题标题】:NHibernate ISession.Get() on entity with composite key throws InvalidCastException具有复合键的实体上的 NHibernate ISession.Get() 抛出 InvalidCastException
【发布时间】:2013-10-24 01:20:36
【问题描述】:

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]]

我在NHibernate Documenatation 中看不到关于 ISession.Get() 和复合键的任何提示。不过,其他answersblog posts 建议我们可以使用匿名类型作为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");

【问题讨论】:

    标签: c# vb.net nhibernate


    【解决方案1】:

    在您链接到的其他答案或博客文章中都没有使用匿名类。他们所做的是使用对象初始化器语法来初始化实体类本身的对象。

    【讨论】:

    • 遇到了同样的问题,我可以发誓我看到有人在匿名类中使用Get,但显然这不起作用。通过对实体本身使用对象初始化器语法效果很好。
    猜你喜欢
    • 1970-01-01
    • 2012-02-16
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 2013-08-26
    • 1970-01-01
    相关资源
    最近更新 更多