27

I get this error:

Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericSet1[IocWinFormTestEntities.People]' to type 'System.Collections.Generic.ISet1[IocWinFormTestEntities.People]'.

The entity:

public class Event 
{
    public Event()
    {
        this.People = new HashSet<People>();
    }
    public virtual Guid Id { get; private set; }

    public virtual ISet<People> People { get; set; }
}

Map override class:

public class EventMapOverride : IAutoMappingOverride<Event>
{
    public void Override(AutoMapping<Event> mapping)
    {
        mapping.HasMany(c => c.People)
            .AsSet()
            .Cascade.AllDeleteOrphan();
    }
}

Generated hbm from fluent automapper:

<set cascade="all-delete-orphan" name="People">
    <key>
        <column name="Event_id" />
    </key>
    <one-to-many class="IocWinFormTestEntities.People, IocWinFormTestEntities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</set>

What's wrong?

Jeroen
  • 60,696
  • 40
  • 206
  • 339
danyolgiax
  • 12,798
  • 10
  • 65
  • 116

3 Answers3

32

Your problem is you are using ISet in System.Collections.Generic namespace but nHibernate expects ISet to be Iesi.Collections.Generic.ISet<>. So change your property definition to

public virtual Iesi.Collections.Generic.ISet<People> People { get; set; }

If you want to use .net 4 ISet<> interface, go through this article

tinonetic
  • 7,751
  • 11
  • 54
  • 79
Eranga
  • 32,181
  • 5
  • 97
  • 96
14

The latest NHibernate uses Iesi.Collections.ISet, not System.Collections.Generic.ISet. You can either reference the Iesi assembly or use System.Collections.Generic.ICollection:

public virtual ICollection<People> People { get; set; }

The ISet interface inherits from ICollection.

eulerfx
  • 36,769
  • 7
  • 61
  • 83
  • But last time I tried ICollection for , NHib was always rewriting it with a plain Array instead of my original HashSet... – JustAMartin Feb 22 '13 at 09:32
4

With Nhibernate 4, using System.Collections.Generic.ISet<> is now the way to go.

The error showcased in this question should no longer occur.

Ted
  • 7,122
  • 9
  • 50
  • 76
Frédéric
  • 9,364
  • 3
  • 62
  • 112