NHibernate eager loading can be done using Fetch
and FetchMany
, as described in NHibernate Linq Eager Fetching on Mike Hadlow's blog.
What is the difference between these two methods and under what circumstance would each be used?
Fetching associations A Linq query may load associated entities or collection of entities. Once the query is defined, using Fetch allows fetching a related entity, and FetchMany allows fetching a collection. These methods are defined as extensions in NHibernate.Linq namespace.
A fetching strategy is the strategy NHibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or overridden by a particular HQL or Criteria query.
A number of NHibernate Linq extensions giving access to NHibernate specific features are defined in the NHibernate.Linq namespace. Of course, the Linq namespace is still needed too. Note: NHibernate has another querying API which uses lambda, QueryOver . It should not be confused with a Linq provider. 18.1. Structure of a Query
Chapter 18. Linq Queries Chapter 18. Linq Queries Chapter 18. Linq Queries NHibernate 3.0 introduces the Linq to NHibernate provider, which allows the use of the Linq API for querying with NHibernate. IQueryable queries are obtained with the Query methods used on the ISession or IStatelessSession.
Fetch
should be used for references and FetchMany
for collections.
This is particularly important because only FetchMany
can be combined with ThenFetchMany
to fetch "grandchildren" collections.
Example:
session.Query<User>() .FetchMany(u => u.Orders) .ThenFetchMany(o => o.OrderItems)
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