很多人在最初使用NHibernate來操作一對多關係時,使用了 <set>標籤,如:
<set name="Students">
<key column="CId"/>
<one-to-many class="NHStusManagerApp.Student"/>
</set>
對應類中使用:
public class Classes{
private ISet<Student> _students;
public virtual ISet<Student> Students
{
get { return _students; }
set { _students = value; }
}
}
看上去很普通,但運行時會報錯如下:
無法將類型爲“NHibernate.Collection.Generic.PersistentGenericSet`1[NHStusManagerApp.Student]”的對象強制轉換爲類型“System.Collections.Generic.ISet`1[NHStusManagerApp.Student]”。
報錯的原因很顯然,是類型錯誤,也就是說,配置文件裏的set標籤是告訴NHibernate在實體類中使用Set集合屬性來裝載關聯數據(如:一班裏的50個學生),此時就會使用班級類裏的Students屬性來存儲學員,但此時應該使用:
Iesi.Collections.Generic 下的 ISet,需要添加 Iesi.Collections.dll 程序集.
但如果沒有添加的話,則是使用 System.Collections.Generic下的 ISet.
所以出現這個無法轉換的錯誤.
from:http://www.oumind.com/html/tech/NHibernateUnableCastPersistentGenericSet_20120429.html