Search code examples
nhibernatenhibernate-mappinglazy-loading

NHibernate one to many with LazyLoad off result in n+1 query


i am trying to turn off lazyloading for one-to-many mapping in NHibernate. I have the follow mapping in my entity mapping class. An entity has many addresses, and what I was looking for is one query that basically join the base table to the Addresses table and return me all the result in one request. Instead I see a series of sql query submitted to database for each record in the base table.

HasMany(m => m.Addresses).Not.LazyLoad().Fetch.Join();

i need a way to turn off lazyloading completely.


Solution

  • I think that would be anough:

    HasMany(m => m.Addresses).Not.LazyLoad();

    To get the data with select you should explicitly use "Fetch":

    session.QueryOver<Item>()
       .Fetch(item => item.Addresses).Eager
       .Take(1000)
       .TransformUsing(Transformers.DistinctRootEntity)
       .List();