title: Intercepting NHibernate Lazy-Load behaviour to return null if not connected to a session?
body: <p>This seems like it should be an obvious thing but I've been searching for the answer for hours now with no success.</p>
  
  <p>I'm using NHibernate to persist a domain model, with a service layer that serves an ASP.NET MVC front end (the 'service layer' is currently just a standard class library but may be converted to WCF in the future). The web app asks for the data it wants and specifies the collections on the domain object that it needs, the service layer takes the request, loads the object and required collections (using lazy loading) and passes the object back where it is transformed using AutoMapper to a viewmodel friendly representation.</p>
  
  <p>What I want to be able to do is load the required collections, detach the object from the session and pass it to the front end. However, when AutoMapper tries to map the object this causes a an exception because it's trying to access collections that haven't been initialized and the session is no longer available. I can leave the object connected but in this case the AutoMapper transformation ends up causing all the properties on the object to be lazy-loaded anyway and this won't be an option is we go down the WCF route.</p>
  
  <p>What I want to do is alter this behaviour so that instead of throwing an exception, the collection returns null (or better yet empty) when it is not connected to a session. This was the default behaviour in Entity Framework V1 (which admittedly didn't do auto lazy loading), which I worked with previously but I can't find a way to do it in NH.</p>
  
  <p>Any ideas? Am I on the wrong track here?</p>
  
  <p>EDIT- To be a bit clearer on what I'm trying to achieve, when accessing a collection property I want this behaviour:</p>
  
  <p>Connected to session: lazy-load collection as normal.<br>
  No session: property is null (rather than throw exception)</p>
  
  <p>UPDATE - Following <a href="http://devlicio.us/blogs/billy_mccafferty/archive/2007/12/07/custom-collections-with-nhibernate-part-iii-refactored.aspx" rel="noreferrer">this post</a> by Billy McCafferty, I've managed to implement a solution using IUserCollectionType that seems to work so far. Rather than use the provided PersistentGenericBag as he does though, I had to create new types that changed the behaviour when not connected to the session. It's not perfect and requires some very ugly mappings but at least I don't need to touch my domain objects or client mappings to get it working.</p>