C# 通过反射投射泛型属性
我试图通过名称检索DbContext DbSet属性,但不知道如何处理泛型参数 Load(IQuerable source)方法来自外部dll,我无法修改它 知道我的DbSet prop的属性名(来自实体框架dbcontext类),我想使用该属性值作为DataSource.Load的参数C# 通过反射投射泛型属性,c#,entity-framework,generics,reflection,C#,Entity Framework,Generics,Reflection,我试图通过名称检索DbContext DbSet属性,但不知道如何处理泛型参数 Load(IQuerable source)方法来自外部dll,我无法修改它 知道我的DbSet prop的属性名(来自实体框架dbcontext类),我想使用该属性值作为DataSource.Load的参数 public class DataManager { private MyDbContext _dbContext; public DataManager(MyDbContext dbC
public class DataManager
{
private MyDbContext _dbContext;
public DataManager(MyDbContext dbContext)
{
_dbContext = dbContext;
}
public object Load(string propName)
{
var source = _dbContext.GetType().GetProperty(entityName).GetValue(_dbContext, null);
return DataSourceLoader.Load(source);
}
//DataSourceLoader.Load signature:
//DataSourceLoader.Load<T>(System.Linq.IQueryable<T>)
公共类数据管理器
{
私有mydbcontextu dbContext;
公共数据管理器(MyDbContext)
{
_dbContext=dbContext;
}
公共对象加载(字符串propName)
{
var source=_dbContext.GetType().GetProperty(entityName).GetValue(_dbContext,null);
返回DataSourceLoader.Load(源);
}
//DataSourceLoader.Load签名:
//DataSourceLoader.Load(System.Linq.IQueryable)
更新
更清楚的是:DataSourceLoader.Load从实体集中加载数据;我不关心返回类型,因为它将被序列化并发送到客户端插件
客户端插件使用entitySet名称作为参数,通过ajax调用请求数据。我不希望为我拥有的每个实体集使用不同的方法(或长的switch语句),并静态调用DataSource.Load方法
我想在运行时解析要查询的实体集您可以尝试使用以下方法:
public object Load(string setName)
{
var property = _context.GetType().GetProperties()
.SingleOrDefault(p => p.PropertyType.IsGenericType
&& p.PropertyType.GetGenericArguments()[0].GetProperty(setName) != null);
return property.GetValue(_context) ?? throw new ArgumentOutOfRangeException(setName);
}
按照我的理解,问题是如何在运行时调用泛型方法 通过获取泛型
MethodInfo
定义,通过调用绑定泛型参数并通过方法调用,可以通过反射实现这一点
具体的答案取决于许多因素,如方法是静态的还是实例的,名称是否唯一(重载),等等。您可以在中看到有关这方面的更多详细信息,但最简单的形式是这样的:
var elementType = ((IQueryable)source).ElementType;
var loadMethod = typeof(DataSourceLoader).GetMethod("Load")
.MakeGenericMethod(elementType);
return loadMethod.Invoke(null, new object[] { source });
通过使用该功能,您可以避免所有这些复杂情况。在这种情况下,您只需简单地转换为动态
:
return DataSourceLoader.Load((dynamic)source);
您试图通过提供属性名来加载entities属性值?@user3292642源类型取决于entityName的类型;它是一个DbSet@grmbl是的,这就是我想要做的。整个目标是不必在方法签名中指定T类型。这并不能解决问题var source=\u dbContext.GetType().GetProperty(entityName).GetValue(_dbContext,null);已经在我的代码中检索了该值,但源代码在编译时是typeof(object)。我正在尝试将该值转换为iqerable,以将其用作DataSource.Load(iqerable source)方法的参数。这正是我试图实现的,谢谢