无法转换’NHibernate.Collection.Generic.PersistentGenericBag’类型的对象

public List FindAll() { using (ISession NSession = SessionProvider.GetSession()) { ICriteria CriteriaQuery = NSession.CreateCriteria(typeof(Application)); return (List) CriteriaQuery.List(); } } 

我得到一个exception,其中应用程序类如下:

 public class Application { private string _name; private Developer _developer; private int _id; private List _bugs; public Application() { } public virtual int ApplicationId { get { return _id; } set { _id = value; } } public virtual Developer Developer { get { return _developer; } set { _developer = value; } } public virtual string Name { get { return _name; } set { _name = value; } } public virtual List Bugs { get { return _bugs; } set { _bugs = value; } } } 

System.InvalidCastException:无法将类型为’NHibernate.Collection.Generic.PersistentGenericBag 1[BugTracker.Model.Bug]' to type 'System.Collections.Generic.List对象1[BugTracker.Model.Bug]' to type 'System.Collections.Generic.List 1 [BugTracker.Model.Bug]’。

这是application.hbm.xml:

                 

我是Nhibernate的新手,发现它非常复杂。 我真的看不出这个问题。 exception发生在Application Class Constructor的最后一行。

尝试将您的Bugs属性设置为IList。 你需要使它成为通用的。 问候。

List<>()方法未返回List ,因此您无法将其强制转换为List

相反,您应该调用ToList()来复制到List() 。 (之后你不需要演员)

你需要投射到IList。 Nhiberante使用dependency injection,你需要使用接口让它发挥其魔力。

我会告诉你另一次这种情况,大多数人都不知道。 如果您有两列具有相同名称但具有不同类型的列,则会遇到此问题。 例如,假设您根据某个ID进行连接,结果集如下

 Id, Name, CreatedDate, Id, ExpirationDate 

如果第一个Id列的数据类型是uniqueidentifier,并且第二个id列的数据类型是int,那么你将获得

 Input string 'f49f503d-70d5-4fbb-8aa2-a0bd0113ff4d' was not in the correct format. ----> System.InvalidCastException : Unable to cast object of type 'System.Guid' to type 'System.IConvertible'. 

因为NHibernate会混合两列,因为它们具有相同的名称/键。 要解决此问题,只需通过别名为列添加唯一名称:

 select Id as IDOne, Name, CreatedDate, Id as IDTwo, ExpirationDate from Table1 t join Table2 t2 on t.Name = t2.Name 

这应解决您对.List()方法的任何问题。

注意:不要将List()与NHibernate中的List混淆。 一个是强类型,另一个当然不是。 List还会自动为您解析结果集,而不是为您提供弱类型的IList。 就我而言,我只使用普通的旧List()。

将您的代码更改为:

 public virtual IList Bugs { get { return _bugs; } set { _bugs = value; } } 

请注意,Bugs是IList而不是List