Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load all entities attached to an object (ignore lazy loading)

Tags:

c#

nhibernate

I wonder if there is a way to tell NHibernate to fetch all data from the DB into the object-graph, no matter if in the mapping-files lazy-loading is set to true. Is there such a function?

like image 728
sl3dg3 Avatar asked May 02 '11 15:05

sl3dg3


2 Answers

There are two options that I'm aware of:

Use the NHibernateUtil class

For example:

Order fromDb;
using (ISession session = SessionFactory.OpenSession())
{
    fromDb = session.Get<Order>(_order.Id);
    NHibernateUtil.Initialize(fromDb.Customer);
}

That will force eager loading of the Customer entity.

Use HQL fetch

If you're using HQL to fetch your entities, just use the fetch keyword in order to force eager loading:

from Order o
inner join fetch o.OrderLines
inner join fetch o.Customer
where o.Id = :id

In that example, OrderLines and Customer will be eager loaded.

More details here.

like image 129
rsenna Avatar answered Oct 08 '22 12:10

rsenna


You can also specify eager fetching in your criterias, for the selected collections:

session.CreateCriteria(typeof(Post))
.SetFetchMode("Comments", FetchMode.Eager)
.List();

You can also combine this with Future<>() invokations for better performance.

like image 44
jishi Avatar answered Oct 08 '22 13:10

jishi