title: How to apply WHERE condition to EF .Include() when building up EF query
body: <p>I have the following 2 classes:</p>
  
  <pre><code>public class Rule
  {
      public int Id { get; set; }
      public string RuleValue { get; set; }
      public bool IsActive { get; set; }
      public SharedRuleType RuleType { get; set; }
      public List&lt;Exclusion&gt; Exclusions { get; set; }
  }
  
  public class Exclusion
  {
      public int Id { get; set; }
      public int InstanceId { get; set; }
      public int SiteId { get; set; }
      [ForeignKey( "RuleId" )]
      public int RuleId { get; set; }
      public Rule Rule { get; set; }
  }
  </code></pre>
  
  <p>I then have an EF query that brings back 'all active' <code>Rules</code>, and I need it to .Include <code>Exclusions</code> for each <code>Rule</code> (if there are any) BUT only <code>Exclusions</code> that have been assigned the specified <code>InstanceId</code>. So the filtering is being done against the <code>Exclusions</code> property, rather than filtering out <code>Rules</code>.</p>
  
  <p>I also have a few conditions as I build up my EF query that I need to take into consideration.</p>
  
  <p>Here is my query at the moment:</p>
  
  <pre><code>public async Task&lt;List&lt;Rule&gt;&gt; GetRules(int instanceId, SharedRuleType ruleType, string searchTerm)
  {
      using ( var context = new MyDbContext() )
      {
          var query = context.Set&lt;Rule&gt;()
              .Include( r =&gt; r.Exclusions ) // *** Currently returns ALL exclusions but I only want ones where InstanceId == instanceId(param) ***
              .Where( r =&gt; r.IsActive );
  
          if ( !string.IsNullOrEmpty( searchTerm ) )
          {
              query = query.Where( r =&gt; r.RuleValue.Contains( searchTerm ) );
          }
  
          if ( ruleType != SharedRuleType.None )
          {
              query = query.Where( r =&gt; r.RuleType == ruleType );
          }
  
          return await query.ToListAsync();
      }
  }
  </code></pre>
  
  <p>I tried applying a .Where within the <code>.Include()</code> in an attempt to only include the relevant <code>Exclusions</code> (based on <code>instanceId</code>) but found out you can't do that. I hunted around and found some examples where people had used an anonymous type, but I couldn't get this working when building up the query piece by piece as I'm doing here.</p>
  
  <p>So, I don't know how I can accomplish this as I really don't want to be returning 'every' <code>Exclusion</code> for each <code>Rule</code>, when I don't need every <code>Exclusion</code> returned.</p>