dotnetcoder
dotnetcoder

Reputation: 3601

how to create a readonly session in nHiberate?

Is it possible to creat a readonly connection in nHibernate ?

Read-only : where nHibernate will not flush out any changes to the underlying database implicitly or explicitly.

When closing a nhibernate connection it does automatically flush out the changes to the persistent object.

Setting the flush mode to never is one way - but is reversable (i.e some code can reset the flush mode).

Upvotes: 16

Views: 8252

Answers (4)

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

There is a newer readonly feature in NHibernate (I don't know which version, but it's in 3.3.0 for sure). You can set the session to read only using this:

session.DefaultReadOnly = true

It disables the cache for old values and therefore improves performance and memory consumption.

There is a chapter about read-only entities in the NHibernate reference documentation.

Upvotes: 2

Jafin
Jafin

Reputation: 4381

Take a look at Read Only entities that became available in NHibernate 3.1 GA https://nhibernate.jira.com/browse/NH-908

Upvotes: 6

Jim
Jim

Reputation: 16022

Accumulating updates, and just never flushing seems like a bad solution to me. I posted a similar question. The solution provided uses a different approach. All the events are set to empty, and thus ignored. My feeling is that it's a better approach.

I am surprised that this is not easier to do. I like the entity framework approach of using an extension method .AsNoTracking() which ensures that read only queries remain that way.

How to create an NHibernate read-only session with Fluent NHibernate that doesn't accumulate updates?

Upvotes: 0

Stuart Childs
Stuart Childs

Reputation: 3305

I think you've already found the solution, setting flush mode to never. Yes, it is changeable but even if it wasn't, code could simply create another session that had a different flush mode.

I think the appropriate solution is to suggest read-only with session.FlushMode = FlushMode.Never and enforce it by using a connection to the database that only has SELECT permissions (or whatever is appropriate for your situation). Maintaining separate ISessionFactory factories might help by allowing something like ReadOnlySessionFactory.Create().

Upvotes: 14

Related Questions