title: Entity Framework Core - dynamic filtering
body: <p>I'm having an issue retrieving correct result from database using Entity Framework Core. </p>
  
  <p>Here is my <code>Article</code> table:</p>
  
  <p><a href="https://i.stack.imgur.com/GCToi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GCToi.jpg" alt="enter image description here"></a></p>
  
  <p>I would like to create dynamic filter using <code>IQueryable</code> that will return the following results:</p>
  
  <pre><code>Select a.Id, a.Name, a.BrandId, a.GenderId
  from dbo.Articles a
  where GenderId in (1)
    and BrandId in (1, 2, 3)
  </code></pre>
  
  <p>which returns:</p>
  
  <p><a href="https://i.stack.imgur.com/UmmYh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UmmYh.jpg" alt="enter image description here"></a></p>
  
  <p>This is my controller action:</p>
  
  <pre><code>public async Task&lt;IActionResult&gt; Clothes()
  {
      var model = new ArticleFilterViewModel();
      model.Genders.AddRange(new int[1] { 1 });
      model.Brands.AddRange(new int[3] { 1, 2, 3 });
      var result = await articleSerivce.GetFilteredUsers(model);
      return View(result);
  }
  </code></pre>
  
  <p>Here is my repository method for fetching filtered articles:</p>
  
  <pre><code>public ICollection&lt;Article&gt; GetFilteredUsers(ArticleFilter filter)
  {
      var articles = GetAll();
      articles = FilteredByBrand(articles, filter.Brands);
      articles = FilteredByGender(articles, filter.Genders);
      var result = articles.ToList();
      return result;
  }
  
  IQueryable&lt;Article&gt; FilteredByBrand(IQueryable&lt;Article&gt; articles,  List&lt;int&gt; items)
  {
      return articles.WhereIf(items.IsNotNullOrEmpty(),  x =&gt; items.Contains(x.BrandId));
  }
  
  IQueryable&lt;Article&gt; FilteredByGender(IQueryable&lt;Article&gt; articles, List&lt;int&gt; items)
  {
       return articles.WhereIf(items.IsNotNullOrEmpty(), x =&gt; items.Contains(x.GenderId));
  }
  </code></pre>
  
  <p>After this code is executed I get the following:</p>
  
  <p><a href="https://i.stack.imgur.com/IsNoG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IsNoG.jpg" alt="enter image description here"></a></p>
  
  <p>I get 3 articles as a result instead of 2 (Article Id's: 2,3,2). </p>
  
  <p>Any idea what I'm doing wrong?</p>