85

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.List1[System.Int32]'."

I am not sure if I have mapped the property EntityIds correctly. Please guide.

Thank you!

Mauricio Scheffer
  • 96,120
  • 20
  • 187
  • 273
inutan
  • 9,740
  • 25
  • 74
  • 119

2 Answers2

161

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>

Mauricio Scheffer
  • 96,120
  • 20
  • 187
  • 273
  • 1
    Thank you! solved the issue. Can you please elaborate a little when you say 'NHibernate can inject it with its own collection implementation.' – inutan Oct 28 '09 at 17:26
  • It's explained here: http://www.surcombe.com/nhibernate-1.2/api/html/T_NHibernate_Collection_IPersistentCollection.htm – Mauricio Scheffer Oct 28 '09 at 20:19
  • 2
    This link no longer exists. An updated one or the brief content would be much appreciated. – Noich Jul 04 '11 at 12:32
  • 1
    @Noich: http://elliottjorgensen.com/nhibernate-api-ref/NHibernate.Collection/IPersistentCollection.html – Mauricio Scheffer Jul 04 '11 at 12:46
  • 2
    I am confused by the number of people on stackoverflow complaining about dead links. Has nobody heard of archive.org? https://web.archive.org/web/20091105034326/http://elliottjorgensen.com/nhibernate-api-ref/NHibernate.Collection/IPersistentCollection.html – Mauricio Scheffer Nov 29 '18 at 11:39
0

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.

Alex Dresko
  • 4,817
  • 2
  • 35
  • 54