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?
There are two options that I'm aware of:
NHibernateUtil
classFor 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With