Posts

Showing posts from March, 2020

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.