title: Entity Framework - Conditionally include related entities
body: <p>I maintain an API that, based on a request for a list of people, returns a different result set based on the request. For example, some API clients want to get a list of people and a list of their interactions, others want people and a list of their metadata. All this can be specified int he request to the API method that returns people.</p>
  
  <p>This does not appear to work: </p>
  
  <pre><code>using (var dbcontext = new ExampleEntities())
  {
      var query = dbcontext.People.AsQueryable();
      //determined in earlier application logic based on request
      if(includeMetadata)
      {
          query = query.Include("metadata");
      }
      //determined in earlier application logic based on request
      if(includeInteractions) 
      {
          query = query.Include("interactions");
      }
      /* ...SNIP... */
  }
  </code></pre>
  
  <p>What I don't want to do is this:</p>
  
  <pre><code>var query = dbcontext.People.Include("Metadata").Include("interactions");
  </code></pre>
  
  <p>which will mean every request to get a person will include ALL their related entities, even if the requesting API client does not need them.</p>
  
  <p>I also don't want to code every possible combination of logic:</p>
  
  <pre><code>if(includeMetadata &amp;&amp; includeInteractions)
  {
      var query = dbcontext.People.Include("Metadata").Include("interactions");
  
  }
  else if(includeMetadata)
  {
      var query = dbcontext.People.Include("Metadata");
  }
  else if(includeInteractions)
  {
      var query = dbcontext.People.Include("Interactions");
  }
  else
  {
      var query = dbcontext.People;
  }
  </code></pre>
  
  <p>This will result in hard-to-maintain code, however, I realize I could code generate this if needed.</p>