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?
Asked
Active
Viewed 6,173 times
2 Answers
8
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.

rsenna
- 11,775
- 1
- 54
- 60
-
1I see - but then I still need to define in any case what I wan't to fetch and I can't do that implicitly, right? If I have a complex graph (with children of children etc.) I still would need to setup the query? The thing is I wan't to create a copy of a complex graph and I thought I would load and then detach everything. Before detaching, everything needs to be loaded though. – sl3dg3 May 03 '11 at 07:18
-
1That is what NHibernateUtil.Initialize is for. However, if you have a lot of entities it might have some performance issues. – jishi May 03 '11 at 08:24
-
1Not really - or I could do `NHibernateUtil.Initialize(fromDb);` and `Customer` and `OrderLines` would be loaded, which is not the case. – sl3dg3 May 03 '11 at 08:50
8
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.

jishi
- 24,126
- 6
- 49
- 75