R – NHibernate in disconnected scenarios

nhibernatesession

What are your experiences with the latest version of NHibernate (2.0.1 GA) regarding disconnected scenarios?

A disconnected scenario is where I fetch some object graph from NHibernate, disconnect from the session (and database connection), do some changes in the object graph (deleting in collections, adding entities, updating entities) and then reconnect and save….

Best Answer

We tried this in a client-server architecture. Now we are moving to DTO (data transfer objects). This means, the detached entities are not directly sent to the client anymore, but specialized objects.

The main reason to move in this direction is not NHibernate, it is actually the serialization needed to send entities to the client. While you could use lazy-loading (and you will!) while you are attached to the session, you need to get all references from the database to serialize it.

We had lots of Guids instead of references and lots of properties which are mapped but not serialized ... and it became a pain. So it's much easier to copy the stuff you really want to serialize to its own structure.

Besides of that - working detached could work well.

  • Be careful with lazy loading, which will cause exceptions to be thrown when accessing non loaded objects on a detached instance.
  • Be careful with concurrency, the chance that entities had changed while they where detached is high.
  • Be careful if you need some sort of security or even if you want your server alown to make some data changes. The detached objects could potentially return in any state.
Related Topic