Load child objects after closing session

I want to load the sub object after the session is closed, anyway?

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
}

      

+3


source to share


1 answer


We can profit from NHibernate's support for working with individual objects

19.1.4. Initializing Collections and Proxies

...
You can also attach a previously loaded object to a new ISession with or , before accessing uninitialized collections (or other proxies) .No, NHibernate does not do this and certainly should not do it automatically, since it will inject special transaction semantics! ... Merge()

Lock()


The adjusted Load () method will 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 caller:

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 on why we need it. The merge will need to change the link (the old detached object will be lost).
Sometimes it is enough (or even better) to just load the collection as IList<TItem>

directly, through the session, using Where ParentId = current.ID

... just an idea ...

+2


source







All Articles