Ways to perform eager loading via NHibernate

By default we know that lazy loading is enabled in NHibernate. So, let's say if we decide to keep the default, how do we enable eager loading with NHibernate?

There are 2 ways to do that (there are more, but I will mention 2 that you will commonly see):

1. Query<Entity>().Fetch(x => x.ClassA).Fetch(x => x.ClassB);

2. var tempQuery Query<Entity>().Fetch(x => x.ClassA).ToFuture();
    Query<Entity>().Fetch(x => x.ClassB).ToFuture();

    var entityList = tempQuery .ToList();

Do note that Fetch is used to fetch reference, while FetchMany is used to fetch collection. If you are wondering what is the difference between 1 and 2, it is the use of ToFuture to split the SQL statement to multiple queries.

The problem with multiple Fetch in a single LINQ query is that it would result in Cartesian product of the main object, in this case, Entity . Hence, it is not recommended to use multiple Fetch in a single query, but rather use method 2.

A Cartesian product is when duplicated copies are returned from a single query. However, you won't see the duplicated records, because NHibernate would have removed them in the background. You don't want that to happen, do you? If you are dealing with million of records, your server will be in deep trouble.

Comments

Popular posts from this blog

ASP.NET Core service locator pattern

Caching and generic query using NHibernate [.NET Core]