title: Dynamic query building with entity framework core - Build a query "by steps"
body: <p>I'm trying to make a class to perform a dynamic filters, depending on what parameters I'll send to its "filter" method but I'm facing some difficulties on building my query.</p>
  
  <p>It's more easy to explain with my following code, where I'm simply trying to apply some filters basing on what i receive in input:</p>
  
  <pre><code>public class PeopleManager : Controller
      {
          private readonly MyPeopleContext _context;
          public PeopleManager(PeopleContext context)
          {
              _context = context;
          }
  
          public IEnumerable&lt;Person&gt; filter (int? id, string name, int? age)
          {
              var peoplequery = _context.People;
              if(id!=null)
              {
                 peoplequery = peoplequery .Where(p =&gt; p.Id.Equals(id));
              }
  
              if(name!="")
              {
                 peoplequery = peoplequery .Where(p =&gt; p.Name.Contains(name));
              }
  
              if(age!=null)
              {
                 peoplequery  = peoplequery .Where(p =&gt; p.Age.Equals(age));
              }
  
              return peoplequery;
          }
      }
  </code></pre>
  
  <p>Obviously, my code is not working and according to this question that I've found:</p>
  
  <p><a href="https://stackoverflow.com/questions/21969154/cannot-implicitly-convert-type-system-linq-iqueryable-to-system-data-entity-d">Cannot implicitly convert type &#39;System.Linq.IQueryable&#39; to &#39;System.Data.Entity.DbSet&#39;</a></p>
  
  <p>I've managed to edit my code as follows:</p>
  
  <pre><code>public IEnumerable&lt;Person&gt; filter (int? id, string name, int? age)
              {
                  var people = _context.People;
  
                  var peoplequery = from p in people select people;
  
                  if(id!=null)
                  {
                     peoplequery = peoplequery .Where(p =&gt; p.Id.Equals(id));
                  }
  
                  if(name!="")
                  {
                     peoplequery = peoplequery .Where(p =&gt; p.Name.Contains(name));
                  }
  
                  if(age!=null)
                  {
                     peoplequery  = peoplequery .Where(p =&gt; p.Age.Equals(age));
                  }
  
                  return peoplequery;
              }
  </code></pre>
  
  <p>But doing this, I can't access to people's properties like id, name, etc... in my lambda expressions.</p>
  
  <p>How can I build this conditional query without any error?</p>