2016-05-13 176 views
1

我最近將Windows SmartClient解決方案從nHibernate 2.2升級到4.0,並在寫入數據庫時​​收到異常。無法轉換'System.Collections.ArrayList'類型的對象來鍵入'System.Collections.Generic.IEnumerable'

this.session.Save(this.Location); // NHibernate.ISession 
tx.Commit(); // exception thrown here 

例外情況是:

在NHibernate.dll System.InvalidCastException則 '':

該異常是在這個代碼拋出 無法轉換類型的對象'System.Collections.ArrayList' 鍵入'System.Collections.Generic.IEnumerable`1 [System.Object]'。

裏有幾個對象名單被保存,這裏是一對夫婦有代表性的:

protected System.Collections.IList locationList; 
public virtual System.Collections.IList AssociatedLocationList 
{ 
    get 
    { 
     if (this.locationList == null) 
     { 
      this.locationList = new System.Collections.ArrayList(); 
     } 
     return this.locationList; 
    } 
    set { this.locationList = value; } 
} 
protected System.Collections.Generic.IList<Inspection> inspectionList; 
public virtual System.Collections.Generic.IList<Inspection> InspectionList 
{ 
    get 
    { 
     if (this.inspectionList == null) 
     { 
      this.inspectionList = new System.Collections.Generic.List<Inspection>(); 
     } 

     return this.inspectionList; 
    } 
    set { this.inspectionList = value; } 
} 

注意某些具有指定的類型和一些不。

一個建議here被設置爲IList的財產,但我已經有這樣的。

可以做些什麼?

+1

你有沒有考慮在此使用泛型?拋光裸露的物體似乎非常... 2003. –

+0

我添加了另一個代表性的財產,有一個到原來的職位。你是否建議不要造成這個問題? –

+0

轉換將不再存在於通用版本中。 –

回答

2

在NHibernate 4.0中刪除了對持久性非泛型集合的支持。轉換爲泛型集合。

查看NHibernate 4.0 release notes中重大更改的列表。

1

我希望我能理解你的問題,如果是的話,我不確定你需要做空檢查。相反,您的父類應該有一個完全位於另一個表中的位置列表。

這是您的位置列表中的類。

public class Parent 
{ 
    public virtual Guid Id { get; set; } 
    public virtual IList<Location> Locations { get; set; } 

    //This is the mapping for this class. 
    public class ParentMapping : ClassMap<Parent> 
    { 
     Id(x => x.Id).GeneratedBy.Guid(); 

     //This is what relates your location list to this parent. 
     //Notice that in the Location object below, 
     //there's a Owner property which will point back to here. 
     HasMany(x => x.Locations).Cascade.All(); 
    } 
} 

這是定義你的位置類。

public class Location 
{ 
    public virtual Guid Id { get; set; } 
    public virtual Parent Owner { get; set; } 
    public virtual string SomeProperty { get; set; } 

    //This is the mapping for this class. 
    public class LocationMapping : ClassMap<Location> 
    { 
     Id(x => x.Id).GeneratedBy.Guid(); 

     Map(x => x.SomeProperty); 

     //This will relate our property back to the parent. 
     References(x => x.Owner); 
    } 
} 
2

這裏的問題可能是最新版本的NHibernate ..i.e。 4.0

你有以下選項。

1)大多數情況下,新版本支持向後兼容。如果是這種情況,請查找iSession.Save方法的過載版本。您也可能會獲得非泛型。

2)可能新的保存方法只支持泛型類型。你的是非泛型的,即ArrayList。如果您可以將其更改爲Ilist <>,那應該有所幫助。 3)如果你對Ilis沒有控制權,那麼你可以在它們之間寫一個轉換器,它可以將你的Arraylist轉換成Ilist <>,它可以和Save方法一起工作。

希望這會有所幫助。

+0

根據你和@羅伯特哈維的說法,我正在努力爭取#2。這可能需要一段時間。此代碼已有10年曆史。 –

相關問題