gpt4 book ai didi

c# - 对 IQueryable OfType<> 的反射(reflection)

转载 作者:行者123 更新时间:2023-11-30 21:57:24 24 4
gpt4 key购买 nike

我的 Entity Framework 上下文中有一个 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 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(Invoke的第一个参数,即实例用于该方法的对象)!

关于c# - 对 IQueryable OfType<> 的反射(reflection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30775756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com