NHibernate really does not seem to like returning a ReadOnlyCollection, depsite me having implemented what I’ve read in about 30 places as the correct access strategy for a read only collection backed to a private field.
I have the following code in my entity:
private readonly IList<TagAlias> _aliases = new List<TagAlias>();
public IEnumerable<TagAlias> Aliases
{
get
{
return new ReadOnlyCollection<TagAlias>(this._aliases);
}
}
and the following mapping to allow access to the backing field
public sealed class TagMap : ClassMap<Tag>
{
public TagMap()
{
Table("Tag");
Id(x => x.Id).Column("TagId").GeneratedBy.Identity();
Map(x => x.Value).Column("TagName");
HasMany(x => x.Aliases)
.AsSet()
.Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
.KeyColumn("TagId")
.LazyLoad()
.Inverse()
.Cascade.AllDeleteOrphan();
}
}
Why on earth does NHibernate still insist on getting the backing list via the ready only collection when I do something like .Clear(), rather than accessing it like I have told it to in the mapping? I am loath to change my domain model just for the sake of the persistence layer, but NHibernate just doesn’t seem to be wanting to cooperate.
The error I get is “A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance” but it goes away when I just return this._aliases in the property getter.
I generally use collections like this and don’t have problems:
I’m not sure of exactly how you are using your collections to get this error but I generally have add and remove methods for my collections inside the classes. If this doesn’t help you maybe you could post the example that causes that error.
Here is a related article I posted several months back:
Exposing HasMany and ManyToMany relationships as IEnumerable