开发者

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

开发者 https://www.devze.com 2023-03-01 21:48 出处:网络
I wonder if th开发者_运维百科ere 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 functio

I wonder if th开发者_运维百科ere 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:

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消