无法将类型为 NHibernate.Collection.Generic.PersisentGenericBag 的对象强制转换为列表

我有一个名为 ReportRequest 的类:

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 映射为:

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();
}
}

现在,我将这个类的一个对象创建为

ReportRequest objReportRequest = new ReportRequest(2, new List<int>() { 11, 12, 15 });

并尝试使用以下命令在数据库中保存对象

session.Save(objReportRequest);

我得到以下错误: “无法强制转换类型为‘ NHibernate. Collection. Generic.PersisentGenericBag1[System.Int32]' to type 'System.Collections.Generic.List1[ System. Int32]’的对象。

我不确定是否正确地映射了属性 EntityIds。 请带路。

谢谢!

36563 次浏览

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>

I found that using ICollection<T> worked where IList<T> did not.

I'm no NHibernate wizard, but I did want to throw a bone to someone else who might land on this issue.