对 IQueryable OfType<> 的反思
Reflection on IQueryable OfType<>
我的 Entity Framework 上下文中有一个 Employees DbSet,可以查询为:
IQueryable employees = _context.Employees;
想法是使用反射执行以下方法:
var result= _context.Employees.OfType<PaidEmployee>()
我扩展了 Employee 对象以创建一个 PaidEmployee class。
我想使用 REFLECTION 查询 PaidEmployee 的上下文。
Assembly asm = Assembly.LoadFrom("MyModel.dll");
Type t = asm.GetType("PaidEmployee");
var ofType = typeof(Queryable).GetMethod("OfType",
BindingFlags.Static | BindingFlags.Public);
var methodinfo = ofType.MakeGenericMethod(t);
var obj = methodinfo.Invoke(employees , null);
当我执行上面的代码时,出现错误:
System.Reflection.TargetParameterCountException was unhandled by user
code HResult=-2147352562 Message=Parameter count mismatch.
Source=mscorlib
StackTrace:
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj,
BindingFlags invokeAttr, Binder binder, Object[] parameters,
CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters,
CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Tests.test_dynamic.TestMethod2() in e:\Projects\Tests\test_dynamic.cs:line 54 InnerException:
尝试
var obj = methodinfo.Invoke(null, new[] { employees });
OfType
是静态的,所以null
obj
([=14=的第一个参数],即方法使用对象的实例)!
我的 Entity Framework 上下文中有一个 Employees DbSet,可以查询为:
IQueryable employees = _context.Employees;
想法是使用反射执行以下方法:
var result= _context.Employees.OfType<PaidEmployee>()
我扩展了 Employee 对象以创建一个 PaidEmployee class。 我想使用 REFLECTION 查询 PaidEmployee 的上下文。
Assembly asm = Assembly.LoadFrom("MyModel.dll");
Type t = asm.GetType("PaidEmployee");
var ofType = typeof(Queryable).GetMethod("OfType",
BindingFlags.Static | BindingFlags.Public);
var methodinfo = ofType.MakeGenericMethod(t);
var obj = methodinfo.Invoke(employees , null);
当我执行上面的代码时,出现错误:
System.Reflection.TargetParameterCountException was unhandled by user code HResult=-2147352562 Message=Parameter count mismatch.
Source=mscorlib StackTrace: at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) at Tests.test_dynamic.TestMethod2() in e:\Projects\Tests\test_dynamic.cs:line 54 InnerException:
尝试
var obj = methodinfo.Invoke(null, new[] { employees });
OfType
是静态的,所以null
obj
([=14=的第一个参数],即方法使用对象的实例)!