views:

38

answers:

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.

A: 

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
Brilliant! I would never have guessed it was a mapping problem. Thank you.
David
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