关于IQueryable OfType<>的反思 [英] Reflection on IQueryable OfType<>

查看:227
本文介绍了关于IQueryable OfType<>的反思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Entity Framework上下文中有一个Employees DbSet,可以查询为:

I have a Employees DbSet in my Entity Framework context that can be queried as:

IQueryable employees = _context.Employees;

这个想法是使用反射执行下面的方法:

The Idea is to execute the below method using Reflection:

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

我扩展了Employee对象来创建PaidEmployee类。
我想使用REFLECTION查询PaidEmployee的上下文。

I have extended the Employee object to create an PaidEmployee class. I want to query the context for PaidEmployee using REFLECTION.

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);

当我执行上面的代码时,它给了我错误:

When I execute the above code, it gives me the error:


System.Reflection.TargetParameterCountException未被用户处理
代码HResult = -2147352562消息=参数计数不匹配。

Source = mscorlib
StackTrace:
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj,
BindingFlags invokeAttr,Binder binder,Object []参数,
CultureInfo culture)$ b $在System.Reflection .RuntimeMethodInfo.Invoke(Object obj,BindingFlags invokeAttr,Binder binder,Object []参数,
CultureInfo culture)
在System.Reflection.MethodBase.Invoke(Object obj,Object []参数)
在Tests.test_dynamic.TestMethod2()中的e:\Projects\Tests\test_dynamic.cs:第54行InnerException:

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:


推荐答案

试试

Try

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

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

The OfType is static, so null obj (the first parameter of Invoke, that is the instance of the object to use for the method)!

这篇关于关于IQueryable OfType&lt;&gt;的反思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆