2 回答
TA贡献1803条经验 获得超6个赞
正如有人在评论中指出的那样,您应该使用泛型:
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>();
}
为了避免为每个实体编写相同的代码 (cache.Set),您可以使用反射,但您的实体应该实现某种通用接口或基类。
例如,假设您的实体实现一个通用接口IEntity:
interface IEntity {}
class Student: IEntity {}
class Teacher: IEntity {}
然后你可以
1 检索所有实现IEntity的类型:
var type = typeof(IEntity);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
2.这样调用GetTableData方法:
MethodInfo method = GetType.GetMethod("GetTableData ");
foreach (var entityType in types)
{
MethodInfo genericMethod = method.MakeGenericMethod(entityType);
genericMethod.Invoke(this, null);
}
TA贡献1794条经验 获得超7个赞
我的解决方案如下;
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 关注
- 133 浏览
添加回答
举报