Capturing NHibernate Lazy-Load behavior to return null if not connected to a session?

This seems to be the obvious thing, but I searched for the answer for several hours without success.

I use NHibernate to save a domain model with a service layer that serves the ASP.NET MVC interface (the “service level” is currently only the standard class library, but can be converted to WCF in the future), the Web application requests the required data and sets collection of the required domain object, the service level accepts the request, loads the object and the necessary collections (using lazy loading) and passes the object back where it is converted using AutoMapper to a viewmodel compatible view.

What I want is to download the necessary collections, disconnect the object from the session and pass it to the foreground. However, when AutoMapper tries to map an object, it throws an exception because it tries to access collections that have not been initialized and the session is no longer available. I can leave the object connected, but in this case, the AutoMapper transformation will end up with all the properties on the object being loaded into lazy anyway, and this will not be an option - we are going along the WCF route.

What I want to do is change this behavior so that instead of throwing an exception, the collection returns null (or still empty) when it is not associated with the session. This was the default behavior in Entity Framework V1 (which admittedly did not do automatic lazy loading) that I worked with earlier, but I can't find a way to do this in NH.

Any ideas? Am I on the wrong track here?

EDIT. To be more clear on achieving what I'm trying to achieve, when accessing a collection property, I need the following behavior:

Connected to the session: a collection of lazy loads as usual.
No session: the property is null (and not an exception for an exception)

UPDATE - after this post from Billy McCafferty, I was able to implement a solution using IUserCollectionType, which seems to work so far. Instead of using the provided PersistentGenericBag as it did, I had to create new types that changed behavior when they were not connected to the session. It is not perfect and requires some very ugly mappings, but at least I don’t need to touch domain objects or client mappings to make it work.

+4
source share
1 answer

The most appropriate solution in this case is probably to check AutoMapper for lazy loaded fields if they were actually loaded using NHibernateUtil.IsInitialized (). Not sure how and if it is possible for Automapper to use this check for all implicit property mappings, though.

An old question, but this is what we did to solve the same problem, hope this helps you establish the right path if someone stumbles upon this problem.

+1
source

All Articles