title: Query an Entity Framework entity without knowing the object type (class/table) in advance
body: <p>I'm wondering, if it's even possible in the first place, how I would go about querying the database (using EF) using an ID and a table name.</p>
  
  <p>For example, writing a function as:</p>
  
  <pre><code>QueryDynamicData(string tableName, long entityID){return GetItem(tableName, entityID);}
  </code></pre>
  
  <p>And could be called like:</p>
  
  <pre><code>var entry = QueryDynamicData("Person", 143);
  </code></pre>
  
  <p>To clarify, this is for a MVC ASP.Net project using Entity Frameworks.</p>
  
  <p>Thanks in advance!</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Following the example from @JPVenson, I came up with the following code. Note that it returns a list of Dictionaries, even though Id is unique, since I'm thinking ahead to when we may want to get all results for a dynamic table instead of just by Id. (This is only proof of concept level)</p>
  
  <pre><code>public List&lt;Dictionary&lt;string, object&gt;&gt; QueryDynamicData(string table, int entityID)
      {
          try
          {
              //Get the table desired based on the table name passed
              PropertyInfo dbSetInfo = DBContext.GetType().GetProperties().FirstOrDefault(p =&gt; p.Name.ToLower().Equals(table.ToLower()));
  
              //Return all results from the table into IQueryable set where Id = entityID passed
              IQueryable anyDbSet = ((IQueryable)dbSetInfo.GetValue(DBContext)).Where("Id=" + entityID);
  
              List&lt;Dictionary&lt;string,object&gt;&gt; listObjects = new List&lt;Dictionary&lt;String, Object&gt;&gt;();
  
              //Iterate through results
              foreach (Object entity in anyDbSet)
              {
                  //Create dictionary of Field Name, Field Value from results
                  Dictionary&lt;string, object&gt; listDBValues = entity.GetType().GetProperties().ToDictionary(propertyInfo =&gt; propertyInfo.Name, propertyInfo =&gt; propertyInfo.GetValue(entity));
  
                  //Add dictionary to list of dictionaries - useful for returning list of found results instead of just one
                  listObjects.Add(listDBValues);
              }
  
              //Return list of dictionaries
              return listObjects;
          }
          catch (Exception e) { }
          return null;
      }
  </code></pre>