0

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.FirstOrDefault()

I want to query the context for FirstOrDefault using REFLECTION.

var firstordefault = typeof(Queryable).GetMethod("FirstOrDefault", BindingFlags.Static | BindingFlags.Public);

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

Ambiguous match found

System.Reflection.AmbiguousMatchException was unhandled by user code
HResult=-2147475171 Message=Ambiguous match found. Source=mscorlib StackTrace: at System.RuntimeType.GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, Type[] types, ParameterModifier[] modifiers) at System.Type.GetMethod(String name, BindingFlags bindingAttr) at Tests.test_dynamic.TestMethod2() in e:\Projects\Tests\test_dynamic.cs:line 70 InnerException:

How can I resolve the ambiguity of this method.

Satyajit
  • 1,971
  • 5
  • 28
  • 51
  • `FirstOrDefault` has two overloads. You need to pass parameter types. With generics, this is tricky. – SLaks Jun 11 '15 at 17:52
  • calling the method as: var firstordefault = typeof(Queryable).GetMethod("FirstOrDefault", BindingFlags.Static | BindingFlags.Public,null,new Type[] { typeof(Queryable) },null); also didn't work. It returned null – Satyajit Jun 11 '15 at 17:54
  • why you need this? try to explain what's behind this requirement... – Matías Fidemraizer Jun 11 '15 at 17:55
  • Its an extension for my previous post: http://stackoverflow.com/questions/30775756/reflection-on-iqueryable-oftype where I will know the object only during runtime – Satyajit Jun 11 '15 at 17:56
  • 1
    http://stackoverflow.com/questions/8338033/how-to-use-getmethod-for-static-extension-method + http://stackoverflow.com/questions/4035719/getmethod-for-generic-method – jjj Jun 11 '15 at 18:14

1 Answers1

0

To resolve this ambiguity, you can use a Linq query as explained in this answer:

MethodInfo mi = typeof(Queryable)
    .GetMethods(BindingFlags.Public | BindingFlags.Static)
    .First(x => x.Name == "FirstOrDefault" &&
                x.GetParameters().Length == 1 &&
                x.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == typeof(IQueryable<>));
Community
  • 1
  • 1
Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62