Mert
Mert

Reputation: 6592

load child objects after session closed

I want to load an objects sub after session closed, anyway to do that?

using (var session = NHibernateHelper<T>.OpenSession())
{
    Foo = session.CreateCriteria(Foo).List<Foo>();
}

using (var session = NHibernateHelper<T>.OpenSession())
{
     Foo.Children.Load();
}


public static void Load<T>(this IList<T> list)
{
     //load foo with Children
}

Upvotes: 3

Views: 384

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123901

We can here profit from NHibernate native support for working with detached objects

19.1.4. Initializing collections and proxies

...
You may also attach a previously loaded object to a new ISession with Merge() or Lock() before accessing uninitialized collections (or other proxies). No, NHibernate does not, and certainly should not do this automatically, since it would introduce ad hoc transaction semantics!
...

The adjusted Load() method would look like this:

public static TEntity LoadCollection<TEntity, TItem>(
        this TEntity entity, 
        Func<TEntity, IList<TItem>> listGetter)
    where TEntity : class
{
    using (var session = NHibernateHelper<T>.OpenSession())
    {
        // here we get brand new - connected - instance of TEntity
        TEntity reAttached = session.Merge<TEntity>(entity);

        NHibernate.NHibernateUtil
            .Initialize(listGetter.Invoke(reAttached));

        return reAttached;
    }
}

And the calling side:

using (var session = NHibernateHelper<T>.OpenSession())
{
    IList<Foo> foos = session.CreateCriteria<Foo>()
            ...
            .List<Contact>();
}

Foo foo = foos.First();

// here we get merged instance with initiated
foo =  foo.LoadCollection(f => f.SomeCollection);

NOTE: It really depends why we need that. Merging will need to change the reference (old detached object will be lost).
Sometimes could be enough (or even better) to just load collection as IList<TItem> directly, via session, using Where ParentId = current.ID... just an idea...

Upvotes: 2

Related Questions