title: Dynamic table name in linq
body: <p>I'm trying to execute some <code>LINQ</code> commands using a dynamic table name. For example, instead of:</p>
  
  <pre><code>var o = (from x in context.users select x);
  </code></pre>
  
  <p>I want to use something like:</p>
  
  <pre><code>var o = (from x in getTableObjectByName("users", context) select x);
  </code></pre>
  
  <p>More or less.  Here's the code I have so far, which both compiles and runs:</p>
  
  <pre><code>using (MySiteEntities ipe2 = new MySiteEntities()) {
      var propinfo1 = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
      var propval1 = propinfo1.GetValue(ipe2, null);
  }
  </code></pre>
  
  <p>That runs, but always returns zero records.  The users table most definitely contains records, and in any case when I call it directly using the first method above I get all of the records as expected.  How can I modify my code to actually pull down records, rather than just an empty collection?</p>
  
  <p><strong>Edit:</strong> I've also tried this:</p>
  
  <pre><code>using (MySiteEntities ipe = new MySiteEntities())
  {
      var prop = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
      Type dbsetType = typeof(DbSet&lt;&gt;);
      dbsetType = dbsetType.MakeGenericType(Type.GetType("MySiteNamespace.user"));
  
      Type t = dbsetType.GetType();
      var val = prop.GetValue(ipe, null);
  }
  </code></pre>
  
  <p>In this case, the code not only runs, but actually returns the results as expected.  However, <code>val</code> is an Object.  I need to cast it to the type <code>DbSet&lt;user&gt;</code>, which would be easy enough, except that the parameter <code>user</code> is only known at runtime....the cast needs to be dynamic as well.  I've tried using <code>Convert.ChangeType(val, t);</code>, but that throws an </p>
  
  <blockquote>
    <p>InvalidCastException (Object must implement IConvertible).</p>
  </blockquote>
  
  <p>How can I convert the <code>val</code> variable to an actually usable object?</p>
  
  <p>No idea if this is relevant, but this is on EntityFramework 4.</p>