I have realized that there are questions that sounds similar to mine but they do not solve my problem. So I want to change a string into a class reference but I cannot change into a variable of type Type, dynamic or anything because then it doesn't work with my generic class.
Please note that the code works when I use a valid class reference. But I have many tables in the DB and it would help a lot if it can be more generic.
Generic class and all works fine here
private class GenericController<T>
{
private CoreGradingDBEntities db = new CoreGradingDBEntities();
public dynamic Get(string Table, string Field, string id)
{
dynamic str = db.Database.SqlQuery<T>("SELECT * FROM " + Table + " WHERE " + Field + " = '" + id + "';").ToList();
return str;
}
}
The method where I am calling the generic class from. When I use a valid class reference it works. So the below code does work.
[Route("api/Values/Table/Field/id")]
public dynamic Get(string Table, string Field, string id)
{
GenericController<Account> generic = new GenericController<Account>();
dynamic d = generic.Get(Table, Field, id);
return d;
}
What I want to do is replace the Account reference. I have tried this but it changes it into a "variable". The Table parameter is the class reference I want in string form. The below code is wrong but you get the idea of what I want to do.
[Route("api/Values/Table/Field/id")]
public dynamic Get(string Table, string Field, string id)
{
Type type = Type.GetType(Table);
GenericController<type> generic = new GenericController<type>(); //Compiler complaining
dynamic d = generic.Get(Table, Field, id);
return d;
}
Any help would be much appreciated. Thanks!