Reputation: 2071
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>()
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 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:
Upvotes: 2
Views: 892
Reputation: 111860
Try
var obj = methodinfo.Invoke(null, new[] { employees });
The OfType
is static, so null
obj
(the first parameter of Invoke
, that is the instance of the object to use for the method)!
Upvotes: 3