C# – nhibernate can you lazyload without proxies

clazy-loadingnhibernate

I've started digging into Nhibernate and although there are many things I do like, there is one ting I dislike: the "generate proxy"/lazy load mechanism. The idea that I have to maintain some sort of reference to the ISession and make sure the entities are associated with the session before accessing a property that might trigger lazy-loading is a bit more plumbing in my viewmodels than I appreciate. In the last ORM mapper I used, we had a different approach to lazy loading which enabled used to disregard the session problem entirely at the cost of less POCO entities. I basically want to do the same thing with nhibernate, with some syntax similar to this:

public class Order
{
    // this will introduced through the ctor using for ex an interceptor and Castle Windsor
    private IOrmService ormService;
    List<OrderLine> details = new List<OrderLine>();

    public IEnumerable<OrderLine> Details
    {
        get
        {
            ormService.LazyLoad(this, o => o.Details);
            return this.details;
        }
    }
}

Where the idea is that the ormService will simply disregard the lazy load request from the entity if the collection has already been loaded (nevermind the state management issue :-)). I looked into the NHibernateUtils-class, which has some Initialized and Initialize-collection methods, but they assume that you are using proxies. Basically, i need a way of telling nhibernate someting like: "hey, populate this property using this session which i'm giving you". The state-management, etc can be handled externally. Is there support for doing this in Nhibernate?

Best Answer

I'm a bit confused with your problem. I feel like following Hibernate best practices should be enough, no need to re-invent what already there. Here are a few comments.

The idea that I have to maintain some sort of reference to the ISession and make sure the entities are associated with the session before accessing a property that might trigger lazy-loading is a bit more plumbing in my viewmodels than I appreciate

If you follow the open session in view pattern, this becomes really easy.

Where the idea is that the ormService will simply disregard the lazy load request from the entity if the collection has already been loaded

That's what the lazy proxy does already.

Basically, i need a way of telling nhibernate someting like: "hey, populate this property using this session which i'm giving you".

That what you do when you detach/attach objects to a session. The lazy items will be loaded according to the session the object is attached to.