title: How to use Queryable.Where when type is set at runtime?
body: <p>I'm implementing the back end of a search/filter UI for an app using EF6. I have code that builds an Expression to use with Queryable.Where for a given DbSet, where the type of the DbSet is determined at runtime (the DBContext has a lot of them, and they may change). The call to Where works fine if I cheat by casting the Expression to a specific type first. Otherwise, I get this error:</p>
  
  <p>'The best overloaded method match for 'System.Linq.Queryable.Where(System.Linq.IQueryable, System.Linq.Expressions.Expression>)' has some invalid arguments'</p>
  
  <p>I'm struggling to find a way to filter the DbSet like this where the underlying 'table' type is provided at runtime. Here's a greatly simplified version of the code to illustrate:</p>
  
  <pre><code>    void ProcessFilter(AppDbContext context, NameValueCollection filters, Type tableType)
      {
          // If tableType == typeof(Organisation), expression is a Expression&lt;Func&lt;Organisation, bool&gt;&gt;
          var expression = GetFilterExpression(filters);
          var dbset = Set(context, tableType);
  
          dynamic dynamicSet = dbset;
  
          // This fails
          var results = Queryable.Where(dynamicSet, expression);
          // see https://stackoverflow.com/questions/4285598/iqueryable-non-generic-missing-count-and-skip-it-works-with-iqueryablet
  
          // Suppose tableType == typeof(Organisation)
          // This works
          var typedExpression = expression as Expression&lt;Func&lt;Organisation, bool&gt;&gt;;
          var typedResults = Queryable.Where(dynamicSet, typedExpression);
  
      }
  
      public static IQueryable Set(DbContext context, Type T)
      {
          // Similar to code in
          // https://stackoverflow.com/questions/21533506/find-a-specified-generic-dbset-in-a-dbcontext-dynamically-when-i-have-an-entity
          var method = typeof(DbContext).GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(x =&gt; x.Name == "Set" &amp;&amp; x.IsGenericMethod).First();
  
          // Build a method with the specific type argument 
          method = method.MakeGenericMethod(T);
  
          return method.Invoke(context, null) as IQueryable;
      }
  </code></pre>