title: Readonly collection properties that NHibernate can work with
body: <p>My domain classes have collections that look like this:</p>
  
  <pre><code>private List&lt;Foo&gt; _foos = new List&lt;Foo&gt;();
  public virtual ReadOnlyCollection&lt;Foo&gt; Foos { get { return _foos.AsReadOnly(); } }
  </code></pre>
  
  <p>This gives me readonly collections that can be modified from within the class (i.e. by using the field _foos).</p>
  
  <p>This collection is mapped as follows (Fluent NHibernate):</p>
  
  <pre><code>HasMany(x =&gt; x.Foos).KeyColumn("ParentClassId").Cascade.All().Inverse().Access.CamelCaseField(Prefix.Underscore);
  </code></pre>
  
  <p>Now when I try to use this collection, I get:</p>
  
  <p>Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag<code>1[Foo]' to type 'System.Collections.Generic.List</code>1[Foo]'.</p>
  
  <p>According to <a href="https://stackoverflow.com/questions/1638593/unable-to-cast-object-of-type-nhibernate-collection-generic-persistentgenericbag">Unable to cast object of type NHibernate.Collection.Generic.PersistentGenericBag to List</a>, this is because the collection needs to be exposed to NHibernate as an interface so that NHibernate can inject one of its own collection classes.</p>
  
  <p>The article suggests using IList instead, but regrettably this interface doesn't include the AsReadOnly() method, messing up my plans to expose only a readonly collection to the outside world.</p>
  
  <p>Can anyone suggest what interface I might use instead, a different approach that meets the same requirements, or an alternative career that doesn't involve this much frustration?</p>
  
  <p>Thanks</p>
  
  <p>David</p>