2 回答

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超6個(gè)贊
正如有人在評(píng)論中指出的那樣,您應(yīng)該使用泛型:
cache.Set(key1, GetTableData<Student>(dbContext));
cache.Set(key2, GetTableData<Class>(dbContext));
cache.Set(key3, GetTableData<Teacher>(dbContext));
public static IEnumerable<T> GetTableData<T> (DBContext dbContext)
{
return dbContext.Set<T>();
}
為了避免為每個(gè)實(shí)體編寫相同的代碼 (cache.Set),您可以使用反射,但您的實(shí)體應(yīng)該實(shí)現(xiàn)某種通用接口或基類。
例如,假設(shè)您的實(shí)體實(shí)現(xiàn)一個(gè)通用接口IEntity:
interface IEntity {}
class Student: IEntity {}
class Teacher: IEntity {}
然后你可以
1 檢索所有實(shí)現(xiàn)IEntity的類型:
var type = typeof(IEntity);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
2.這樣調(diào)用GetTableData方法:
MethodInfo method = GetType.GetMethod("GetTableData ");
foreach (var entityType in types)
{
MethodInfo genericMethod = method.MakeGenericMethod(entityType);
genericMethod.Invoke(this, null);
}

TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
我的解決方案如下;
MethodInfo methodInfo = typeof(CacheSettings).GetMethod("GetTableData");
string[] tablesToBeCached = { "Student", "Class", "Teacher" };
object[] parameters = new object[] { myDBContextObj };
foreach(var tblToBeCached in tablesToBeCached)
{
string key = $"{tblToBeCached}";
MethodInfo getTableDataMethod = methodInfo.MakeGenericMethod(Type.GetType($"Namespace.{tblToBeCached}, AssemblyName"));
cache.Set(key, getTableDataMethod.Invoke(null, parameters));
}
and the GetTableData() method is just one liner (Happy days ??)
public static IEnumerable<T> GetTableData<T>(MyDBContext dbContext) where T : class
{
return dbContext.Set<T>();
}
- 2 回答
- 0 關(guān)注
- 219 瀏覽
添加回答
舉報(bào)