I am wondering if this is possible in the first place, how I will access the database (using EF) using the identifier and name of the table.
For example, writing a function as:
QueryDynamicData(string tableName, long entityID){return GetItem(tableName, entityID);}
And can be called as:
var entry = QueryDynamicData("Person", 143);
To clarify, this is for an ASP.Net MVC project using Entity Frameworks.
Thanks in advance!
EDIT:
Following @JPVenson's example, I came up with the following code. Please note that it returns a list of dictionaries, although the identifier is unique, as I think in advance when we want to get all the results for a dynamic table, and not just using Id. (This is only a proof of concept level)
public List<Dictionary<string, object>> QueryDynamicData(string table, int entityID)
{
try
{
PropertyInfo dbSetInfo = DBContext.GetType().GetProperties().FirstOrDefault(p => p.Name.ToLower().Equals(table.ToLower()));
IQueryable anyDbSet = ((IQueryable)dbSetInfo.GetValue(DBContext)).Where("Id=" + entityID);
List<Dictionary<string,object>> listObjects = new List<Dictionary<String, Object>>();
foreach (Object entity in anyDbSet)
{
Dictionary<string, object> listDBValues = entity.GetType().GetProperties().ToDictionary(propertyInfo => propertyInfo.Name, propertyInfo => propertyInfo.GetValue(entity));
listObjects.Add(listDBValues);
}
return listObjects;
}
catch (Exception e) { }
return null;
}
source
share