2

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.

Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154

1 Answers1

2

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:

  • NHibernate does not dirty-check the entity's simple properties or single-ended associations
  • NHibernate will not update simple properties or updatable
    single-ended associations
  • NHibernate will not update the version of the read-only entity if
    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:

  • NHibernate cascades operations to associations as defined in the entity mapping.
  • NHibernate updates the version if the entity has a collection with changes that dirties the entity;
  • A read-only entity can be deleted.

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.

IdentityMap

In the context the state can be checked by opening the individual entity entry.

hessenmob82
  • 175
  • 12