无法将 NHibernate.Collection.Generic.PersistentGenericBag 类型的对象转换为 List [英] Unable to cast object of type NHibernate.Collection.Generic.PersistentGenericBag to List
问题描述
我有一个名为 ReportRequest 的类:
I have a class called ReportRequest as:
public class ReportRequest
{
Int32 templateId;
List<Int32> entityIds;
public virtual Int32? Id
{
get;
set;
}
public virtual Int32 TemplateId
{
get { return templateId; }
set { templateId = value; }
}
public virtual List<Int32> EntityIds
{
get { return entityIds; }
set { entityIds = value; }
}
public ReportRequest(int templateId, List<Int32> entityIds)
{
this.TemplateId = templateId;
this.EntityIds = entityIds;
}
}
它使用 Fluent Hibernate 映射为:
It is mapped using Fluent Hibernate as:
public class ReportRequestMap : ClassMap<ReportRequest>
{
public ReportRequestMap()
{
Id(x => x.Id).UnsavedValue(null).GeneratedBy.Native();
Map(x => x.TemplateId).Not.Nullable();
HasMany(x => x.EntityIds).Table("ReportEntities").KeyColumn("ReportRequestId").Element("EntityId").AsBag().Cascade.AllDeleteOrphan();
}
}
现在,我创建这个类的一个对象
Now, I create an object of this class as
ReportRequest objReportRequest = new ReportRequest(2, new List<int>() { 11, 12, 15 });
并尝试使用
session.Save(objReportRequest);
我收到以下错误:无法将NHibernate.Collection.Generic.PersistentGenericBag1[System.Int32]"类型的对象转换为System.Collections.Generic.List
1[System.Int32]"."
I get the following error:
"Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag1[System.Int32]' to type 'System.Collections.Generic.List
1[System.Int32]'."
我不确定我是否正确映射了属性 EntityIds.请指导.
I am not sure if I have mapped the property EntityIds correctly. Please guide.
谢谢!
推荐答案
使用集合接口代替具体的集合,这样 NHibernate 可以用自己的集合实现注入它.
Use collection interfaces instead of concrete collections, so NHibernate can inject it with its own collection implementation.
在这种情况下,使用 IList
而不是 List
In this case, use IList<int>
instead of List<int>
这篇关于无法将 NHibernate.Collection.Generic.PersistentGenericBag 类型的对象转换为 List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!