无法将类型为NHibernate.Collection.Generic.PersistentGenericBag的对象转换为List [英] Unable to cast object of type NHibernate.Collection.Generic.PersistentGenericBag to List
问题描述
public class ReportRequest
{
Int32 templateId;
列表< 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; }
}
$ b $ public ReportRequest(int templateId,List< Int32> entityIds)
{
this.TemplateId = templateId;
this.EntityIds = entityIds;
它使用Fluent Hibernate映射为:
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();
$ b $现在我创建这个类的一个对象为
ReportRequest objReportRequest = new ReportRequest(2,new List< int>(){11,12,15});
并尝试将对象保存到数据库中使用
session.Save(objReportRequest);
出现以下错误:
无法投射类型对象 NHibernate.Collection.Generic.PersistentGenericBag 1 [System.Int32]'键入'System.Collections.Generic.List
1 [System.Int32]'。
我不确定是否已经正确映射了属性EntityIds。
请指导
谢谢!
解决方案使用集合接口,而不是具体的集合,所以NHibernate可以注入它自己的集合实现。
在这种情况下,使用 IList< int> / code>而不是列表< int>
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;
}
}
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 });
and try to Save the object in database using
session.Save(objReportRequest);
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]'."
I am not sure if I have mapped the property EntityIds correctly.
Please guide.
Thank you!
解决方案 Use collection interfaces instead of concrete collections, so NHibernate can inject it with its own collection implementation.
In this case, use IList<int>
instead of List<int>
这篇关于无法将类型为NHibernate.Collection.Generic.PersistentGenericBag的对象转换为List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!