Lodewijk
Lodewijk

Reputation: 2391

NHibernate StateLessSession vs DefaultReadOnly

In NHibernate, what is the difference between:

using(var session = _sessionFactory.OpenStatelessSession()) {
    //Do Work
}

and

using(var session = _sessionFactory.OpenSession()) {
    session.DefaultReadOnly = true;
    //Do Work
    session.DefaultReadOnly = false;
}

I only want some entities in certain contexts to be Stateless and others not. I can either use two sessions (one statefull and one stateless) or wrap the queries I want to be stateless in to DefaultReadOnly-calls.

Upvotes: 2

Views: 921

Answers (1)

Dirk Trilsbeek
Dirk Trilsbeek

Reputation: 6023

setting DefaultReadOnly to true just means NHibernate won't track the entities properties and won't update the entity on the database (at least sometimes). It will still keep the entity in its session cache. A stateless session doesn't keep track of its entities in the first place, saving some memory.

If you're only concerned about readonly, you could probably go with a single session and DefaultReadOnly = true. But if you want NHibernate to not use its session cache when loading an entity (for instance, to get the current data from the database, not the data in the session cache from 5 minutes ago), you'd be better served with a stateless session.

Upvotes: 2

Related Questions