我的实体框架上下文中有一个员工DbSet,可以将其查询为:
IQueryable employees = _context.Employees;
其思想是使用反射执行以下方法:
var result= _context.Employees.OfType<PaidEmployee>()
我已经扩展了Employee对象以创建一个PaidEmployee类。我想使用反射查询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未被用户代码HResult=-2147352562 Message=Parameter计数不匹配处理。 在System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj,BindingFlags invokeAttr,binder胶凝剂,Object[]参数,CultureInfo文化)在System.Reflection.RuntimeMethodInfo.Invoke(Object obj,BindingFlags invokeAttr,binder粘合剂,Object[]参数,CultureInfo文化) at System.Reflection.MethodBase.Invoke(Object obj,Object[]参数) at Tests.test_dynamic.TestMethod2(),e:\Projects\Tests\test_dynamic.cs:line 54 InnerException:
发布于 2015-06-11 00:46:12
试一试
var obj = methodinfo.Invoke(null, new[] { employees });
OfType
是静态的,所以null
obj
( Invoke
的第一个参数,即要用于该方法的对象的实例)!
https://stackoverflow.com/questions/30775756
复制