title: How to fetch objects multiple levels deep and wide with NHibernate?
body: <p>I have a case where I need to load about 10 000 objects from database. The data model is something like this:</p>
  
  <pre><code>public class SimulationObject
  {
      public Container Container {get;set;}
      public IList&lt;ResultItem&gt; Results {get;set;}
      public IList&lt;PreviewData&gt; PreviewData {get;set;}
      ...
  }
  
  public class ResultItem
  {
      public IList&lt;SomeDataItem&gt; Items {get;set;}
      ...
  }
  
  public class PreviewData
  {
      public IList&lt;SomeDataItem&gt; Items {get;set;}
      ...
  }
  </code></pre>
  
  <p>This means that I want to query a list of SimulationObjects from database according to some query, and all of it's properties (references) and subitems.</p>
  
  <p>The quantities of collections are the following:</p>
  
  <ol>
  <li>SimulationObject - ca 6000 - 1200, depending on parameters in "where"</li>
  <li>SimulationObject.Results - ca 5 to 40 items</li>
  <li>SimulationObject.Results.Items - ca 0 to 2 items</li>
  <li>SimulationObject.PreviewData - ca 0 to 2 items</li>
  <li>SimulationObject.PreviewData.Items - ca 1 to 3 items</li>
  </ol>
  
  <p>Normally, I'd do it like this:</p>
  
  <pre><code>var query = from sim in session.Query&lt;SimulationObject&gt;()
          where sim.Container.Id == containerId &amp;&amp; ...
              select sim;
  
  query = query.FetchMany(c =&gt; c.Results).ThenFetch(o =&gt; o.Items)...
  </code></pre>
  
  <p>However, I also need to fetch "PreviewData" items for that would create a Cartesian product in my query (meaning PreviewDataAndSubItemsCount x ResultsAndSubItemsCount amount of rows returned) which is very ineffective. Also, as I need to load a LOT of SumulationObjects (about 10000 as sayd earlier), I cannot do lazy loading (10000 queries..and there are other difficulties too, so this isn't even an alternative to consider).</p>
  
  <p>So what are the alternatives ? What strategy would you use to load a complite object graph into memory ?</p>
  
  <p>Thanks.</p>