2013-10-22 36 views
1

對具有組合鍵的實體調用NHibernate的ISession的Get()方法時會引發InvalidCastException。關於帶有組合鍵的實體的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沒有暗示。但是,其他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"); 

回答

2

在鏈接到的其他答案或博客文章中沒有使用匿名類。他們所做的是,他們使用對象初始化器語法來初始化實體類本身的一個對象。

+0

你完全正確。謝謝你打開我的眼睛。 – fan711

+0

出現同樣的問題,可能發誓我看到有人使用匿名類的「Get」,但顯然這是行不通的。使用對象初始化器語法和實體本身很好地工作。 –

相關問題