title: Lazy load nested set
body: <p>I am using Entity Framework with Code First to persist my data.</p>
  
  <p>There is a class with a nested list:</p>
  
  <pre><code>public class AgeGroup
  {
      public BindingList&lt;WeightGroup&gt; WeightGroups { get; set; }
  }
  </code></pre>
  
  <p>The database context consists of</p>
  
  <pre><code>public DbSet&lt;AgeGroup&gt; AgeGroups { get; set; }
  </code></pre>
  
  <p>I am creating a window, where the user can modify <code>AgeGroup</code>s and their according <code>WeightGroup</code>s. In order to bind a <code>ListBox</code>'s <code>ItemsSource</code> property to the <code>AgeGroups</code>, I load them and bind to the <code>Local</code> set:</p>
  
  <pre><code>ctx.AgeGroups.Load();
  vm.AgeGroups = ctx.AgeGroups.Local;
  </code></pre>
  
  <p>Up to here, the <code>WeightGroups</code> are not loaded, because they are not needed. So far, so good.</p>
  
  <p>When the user chooses an <code>AgeGroup</code> for modification, its <code>WeightGroups</code> have to be loaded. Up to now I do it like this (in the setter of the <code>SelectedAgeGroup</code> property):</p>
  
  <pre><code>value.WeightGroups = (from age in ctx.AgeGroups
                        where age.Id == value.Id
                        select age.WeightGroups).Single();
  </code></pre>
  
  <p>However, this seems a bit clumsy. First of all, because a new list is set instead of filling the existing one. Furthermore, there are some behaviours, which are unwanted. This includes e.g. the following:</p>
  
  <ul>
  <li>If a <code>WeightGroup</code> is modified and <code>SaveChanges()</code> is called, the old group is still there and additionally a new one with the modified values.</li>
  <li>If the user removes an entity with <code>SelectedAgeGroup.WeightGroups.Remove(...)</code> and <code>SaveChanges()</code>, the deleted rows are still there.</li>
  </ul>
  
  <p>I assume, the reload of weight groups as listed above is causing this.</p>
  
  <p>How would correct Lazy Loading look like in this case? Ideally, the necessary <code>WeightGroups</code> are loaded automatically by the framework. I read about using an <code>IQueryable</code> instead of <code>BindingList</code> for the <code>WeightGroups</code> property. But this interface does not have methods for inserting and removing entities. Furthermore, if I just exchange the types, not even the <code>AgeGroups</code> are loaded at all.</p>