16

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).

dotnetcoder
  • 3,431
  • 9
  • 54
  • 80
  • I know this is an ancient (in Internet time) question, but what's the reason for your concern about this being "reversable"? – Kenny Evitt May 13 '14 at 13:32

4 Answers4

14

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().

Stuart Childs
  • 3,295
  • 1
  • 19
  • 11
6

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

Daniel Schilling
  • 4,829
  • 28
  • 60
Jafin
  • 4,153
  • 1
  • 40
  • 52
1

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.

Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
0

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?

Community
  • 1
  • 1
Jim
  • 14,952
  • 15
  • 80
  • 167
  • No, updates don't accumulate after setting session.FlushMode = FlushMode.Never. I checked it by overriding SaveOrUpdateEventListeners like in your question, and listener does not called with FlushMode.Never. In your solution NoOpEventListener is called for each change – razon Jan 11 '15 at 18:17