NHibernate Pitfalls: Lazy Properties and Closed Sessions

This is part of a series of posts about NHibernate Pitfalls. See the entire collection here.

Beware when accessing previously un-accessed lazy properties (simple properties, many to one, one to one, many to many, one to many) outside the scope of its originating session: it will result in an exception, because the session is no longer accessible.

One place where this commonly occurs is when returning entities from WCF web services and there are two ways to get over this:

  • Force loading of all associations beforehand;
  • Instantiating a custom Data Transfer Object with all required properties loaded.
   1: //load an entity with all of its associations
   2: var customer = session.Query<Customer>().Fetch(x => x.Orders).Where(x => x.Id == CustomerId).Single();
   4: //load an entity into a custom data transfer object
   5: var customerDTO = session.Query<Customer>().Where(x => x.Id == CustomerId).Select(x => new CustomerDTO(x)).Single();                


1 Comment

Comments have been disabled for this content.