I'm working on a project which uses NHibernate as an ORM.
A fairly large number of entities can be loaded into the session as 'readonly' since they should not be updated after retrieval.
I've tried to do this in 2 different ways:
var entity = criteria.UniqueResult<MyType>();
_session.SetReadOnly(entity, true);
or:
criteria.SetReadOnly(true);
In both ways however, I can see that the entity is present in the PersistenceContext of the ISession.
Is this normal ? I'd expect that, since the entity is readonly/immutable, it should not be present in the PersistenceContext. The entity type is a complex type; it has multiple associations to other types.
There are some limitations to the Read-Only functionality in nhibernate. The name of the function lets one expect a harder warranty of preventing object changes. If you look at the documentation (http://nhibernate.info/doc/nh/en/index.html#readonly) there are many exceptions that could lead to unintended changes in the database.
From the docs:
When an entity is read-only:
single-ended associations
only simple properties or single-ended updatable associations are
changed
In some ways, NHibernate treats read-only entities the same as entities that are not read-only:
Considering your expectations it think Objects are always added to the Persistence-Context even if they are load Read-Only. Otherwise the Identity-Map -Pattern would not hold. In the Persistence-Context there is a Flag that signals that an entity is Read-Only.
In the context the state can be checked by opening the individual entity entry.