Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readonly collection properties that NHibernate can work with

My domain classes have collections that look like this:

private List<Foo> _foos = new List<Foo>();
public virtual ReadOnlyCollection<Foo> Foos { get { return _foos.AsReadOnly(); } }

This gives me readonly collections that can be modified from within the class (i.e. by using the field _foos).

This collection is mapped as follows (Fluent NHibernate):

HasMany(x => x.Foos).KeyColumn("ParentClassId").Cascade.All().Inverse().Access.CamelCaseField(Prefix.Underscore);

Now when I try to use this collection, I get:

Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag1[Foo]' to type 'System.Collections.Generic.List1[Foo]'.

According to Unable to cast object of type NHibernate.Collection.Generic.PersistentGenericBag to List, 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.

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.

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?

Thanks

David

like image 257
David Avatar asked Dec 06 '22 01:12

David


1 Answers

The AsReadOnly() method isn't the only way to get a ReadOnlyCollection.

private IList<Foo> _foos = new List<Foo>();
public virtual ReadOnlyCollection<Foo> Foos { get { return new ReadOnlyCollection<Foo>(_foos); } }

Another hoop jumped.

like image 174
David Avatar answered Mar 02 '23 18:03

David