title: Dynamically cast IEnumerable to IQueryable or dynamically call AsQueryable with LINQ Expressions
body: <p>I am creating LINQ query dynamically, and I am doing OK so far. </p>
  
  <p>But I am stuck where I thought I wouldn't be. At a certain point in building that query, I need to access EnityCollection of an entity. Something like this:</p>
  
  <pre><code>Expression collection = Expression.Property(entity, typeof(EntityType).GetProperty("CollectionOfRelatedEntities"));
  </code></pre>
  
  <p>Then, I would call "Where" LINQ method upon that collection:</p>
  
  <pre><code>MethodCallExpression AfterWhere = Expression.Call(
                          typeof(Queryable),
                          "Where",
                          new Type[] { typeof(RelatedEntity) },
                          collection,
                          Expression.Lambda&lt;Func&lt;RelatedEntity, bool&gt;&gt;(predicate, new ParameterExpression[] { paramOfRelatedEntity }));
  </code></pre>
  
  <p>And normally that would work. In this case it won't because collection is IEnumerable and I need it to be IQueryable in order "Where" to work.</p>
  
  <p>I tried this:</p>
  
  <pre><code>Expression.Convert(collection, typeof(IQueryable&lt;RelatedEntity&gt;);
  </code></pre>
  
  <p>but it says unable to cast because EntityCollection doesn't implement IQueryable.</p>
  
  <p>I statically use AsQueryable to achieve what i need here, so i tried mimicking that dynamically:</p>
  
  <pre><code>Expression.Call(collection, typeof(EntityCollection&lt;RelatedEntity&gt;).GetMethod("AsQueryable"));
  </code></pre>
  
  <p>but I get null reference exception. I can't reach it via reflection. This AsQueryable method is extension method, it is static, defined in Queryable class, so i tried:</p>
  
  <pre><code>Expression.Call(collection, typeof(Queryable).GetMethod("AsQueryable", BindingFlags.Static)); 
  </code></pre>
  
  <p>Same result: "Value cannot be null".</p>
  
  <p>I am reaching my limits here, and I am fresh out of ideas.</p>
  
  <p>So, I am asking you:</p>
  
  <p>How can I dynamically cast IEnumerable to IQueryable?</p>