I am using .net core 2.1 with entityframework core.
I have different models/entities/types defined in my project. e.g. Student, Class, Teacher.
I am getting the table data for these models to set in my cache.
At the moment, I am doing this;
string[] tablesToBeCached = { "Student", "Class", "Teacher" };
foreach(var table in tablesToBeCached)
{
cache.Set(key, GetTableData(dbContext, table));
}
and the function GetTableData() is defined as follows;
public IEnumerable<object> GetTableData(DBContext dbContext, string tableName)
{
switch (tableName)
{
case "Student":
return dbContext.Student;
case "Class":
return dbContext.Class;
case "Teacher":
return dbContext.Teacher;
default:
return null;
}
}
I want this code to be smart and short.
I tried following, but didn't work; (The error is 'x' is a variable but is used like a type)
List<object> entities = new List<object> { typeof(Student), typeof(Class), typeof(Teacher) };
entities.ForEach(x => GetTableData(x, dbContext));
public IEnumerable<object> GetTableData(object x, DBContext dbContext)
{
return dbContext.Set<x>();
}
Can someone please help? Is it even possible in C#?