【问题标题】:Reflection on IQueryable OfType<>对 IQueryable OfType<> 的反思
【发布时间】:2015-06-11 08:40:48
【问题描述】:

我的实体框架上下文中有一个Employees DbSet,可以这样查询:

IQueryable employees = _context.Employees;

想法是使用反射执行以下方法:

var result= _context.Employees.OfType<PaidEmployee>()

我已经扩展了 Employee 对象来创建一个 PaidEmployee 类。 我想使用 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 未被用户处理 code HResult=-2147352562 Message=参数计数不匹配。
源=mscorlib 堆栈跟踪: 在 System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(对象 obj, BindingFlags invokeAttr,Binder binder,Object[]参数, CultureInfo文化) 在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] 参数, CultureInfo文化) 在 System.Reflection.MethodBase.Invoke(对象 obj,对象 [] 参数) 在 e:\Projects\Tests\test_dynamic.cs:line 54 InnerException 中的 Tests.test_dynamic.TestMethod2():

【问题讨论】:

    标签: c# entity-framework generics reflection


    【解决方案1】:

    试试

    var obj = methodinfo.Invoke(null, new[] { employees });
    

    OfType是静态的,所以nullobjInvoke的第一个参数,即方法使用的对象的实例)!

    【讨论】:

      猜你喜欢
      • 2015-08-27
      • 1970-01-01
      • 2011-04-09
      • 1970-01-01
      • 2010-10-29
      • 2019-01-27
      • 1970-01-01
      • 2011-01-14
      • 2019-04-25
      相关资源
      最近更新 更多