Monday, August 13, 2012

NHibernate Linq force join

NHibernate uses lazy loading, so to prevent a 1-n query, you have to tell NHibernate to fetch associations as well. With Linq to NHibernate this is done with Fetch and FetchMany. In the example below you see a call to get an Order with the forced join with the associations I needed in a view.
var orders = session.Query<Order>()
   .FetchMany(o => o.OrderItems)
      .ThenFetch(oi => oi.Item)
         .ThenFetch(i => i.Manufacturer)
   .FetchMany(o => o.AdditionalItems)
   .FetchMany(o => o.Rebates)
   .Fetch(o => o.Customer)
   .Where(o => o.PeriodStart <= toDate)
   .Where(o => fromDate <= o.PeriodEnd)
   .OrderBy(o => o.PeriodStart);

No comments: