【问题标题】:Unable to cast object of type NHibernate.Collection.Generic.PersistentGenericBag to List无法将 NHibernate.Collection.Generic.PersistentGenericBag 类型的对象转换为 List
【发布时间】:2019-03-27 02:55:19
【问题描述】:

我有一个名为 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.PersistentGenericBag1[System.Int32]' to type 'System.Collections.Generic.List1[System.Int32]' 的对象。

我不确定我是否正确映射了属性 EntityIds。 请指导。

谢谢!

【问题讨论】:

  • 您确定要整数列表而不是相关实体列表吗?

标签: nhibernate fluent-nhibernate nhibernate-mapping


【解决方案1】:

使用集合接口而不是具体的集合,因此 NHibernate 可以用自己的集合实现注入它。

在这种情况下,请使用IList&lt;int&gt; 而不是List&lt;int&gt;

【讨论】:

【解决方案2】:

我发现使用ICollection&lt;T&gt; 可以在IList&lt;T&gt; 没有的地方使用。

我不是 NHibernate 巫师,但我确实想向可能涉及此问题的其他人扔一根骨头。

【讨论】:

  • 这取决于您的收藏是如何映射的。对于bag,您可以使用IList&lt;T&gt; 和设置-ISet&lt;T&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 2022-01-22
相关资源
最近更新 更多