Oliver
Oliver

Reputation: 11607

How many sessions can I keep open in NHibernate?

I am writing a desktop application using NHibernate to connect to the database.

My Models have a session that is opened when the model is initialized, and closed when the model is disposed. This is ok when I have one model per form, as the number of open sessions is the same as the number of open windows - a small number.

I am now making a form that lists many models, so if the form lists 50 models, there will be 50 open sessions. I suspect that this may be a problem.

How many open sessions can I have in NHibernate? Should I have only a small number, or can I have as many open sessions as I need?

Upvotes: 0

Views: 731

Answers (1)

Martin Ernst
Martin Ernst

Reputation: 5679

It depends how long you keep your sessions open for and what you do with them. The session itself is pretty lightweight and doesn't necessarily open a connection to the database.

However I think that having 50 open sessions for 1 form is not the best design. I would suggest using a session as a "unit of work" in that when you want to do something (such as present some data, or update some data, or list a bunch of entities), you open the session, do your work, and then dispose of the session. This can cause some issues with lazy loading and data-binding, but you can work around those by fetching the required associations.

You can reconnect entities that you have loaded in one session into another by using session.Lock(entity, LockMode.None), so you don't need to have the session open between user interactions.

Upvotes: 2

Related Questions