Query an Entity Framework entity without knowing the object type (class/table) in advance

Viewed 3889

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.

For example, writing a function as:

QueryDynamicData(string tableName, long entityID){return GetItem(tableName, entityID);}

And could be called like:

var entry = QueryDynamicData("Person", 143);

To clarify, this is for a MVC ASP.Net project using Entity Frameworks.

Thanks in advance!

EDIT:

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)

public List<Dictionary<string, object>> QueryDynamicData(string table, int entityID)
    {
        try
        {
            //Get the table desired based on the table name passed
            PropertyInfo dbSetInfo = DBContext.GetType().GetProperties().FirstOrDefault(p => 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<Dictionary<string,object>> listObjects = new List<Dictionary<String, Object>>();

            //Iterate through results
            foreach (Object entity in anyDbSet)
            {
                //Create dictionary of Field Name, Field Value from results
                Dictionary<string, object> listDBValues = entity.GetType().GetProperties().ToDictionary(propertyInfo => propertyInfo.Name, propertyInfo => 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;
    }
2 Answers
Related