1

I have a class which uses an ISet as a collection type as below:

  public class Client
  {
    private ISet<Contact> _contacts = new HashedSet<Contact>();
    public virtual ISet<Contact> Contacts { get { return _contacts; } }
  }

I don't want the collection itself to be able to be modified externally. However, if I change the property's type to IEnumerable as below:

  public class Client
  {
    private ISet<Contact> _contacts = new HashedSet<Contact>();
    public virtual IEnumerable<Contact> Contacts { get { return _contacts; } }
  }

Then whenever I try to use this class I get the NHibernate error:

System.InvalidCastException: Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag1[Kctc.BusinessLayer.ProbateAssist.Entities.Contact]' to type 'Iesi.Collections.Generic.ISet1[Kctc.BusinessLayer.ProbateAssist.Entities.Contact]'.

What gives? How can I make the public version of the collection read only?

NB I've also tried to use ReadOnlyCollection, and get the same error.

David
  • 15,750
  • 22
  • 90
  • 150
  • 1
    You should show what your nhibernate config files look like (or what is your fluent configuration if you use FluentNhibernate) – samy Oct 26 '10 at 21:22

1 Answers1

1

You are probably using Fluent automapping, which is guessing the type as Bag instead of Set based on the interface type. You'll have to override it in that case.

IEnumerable<T> works fine when mapping manually or with XML.

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • Brilliant! I would never have guessed it was a mapping problem. Thank you. – David Oct 27 '10 at 07:58
  • For posterity, I fixed this problem by adding .AsSet() to the end of the HasMany line for the Contacts collection in the Client mapping file. – David Oct 27 '10 at 07:59