Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous match found exception

Well this one used to work great, before upgrading to .NET 5 from net core 3.1

The extension method that produces the error is

public static IQueryable Set(this myContext context, Type T)
{
    MethodInfo method = typeof(myContext).GetMethod(nameof(myContext.Set), BindingFlags.Public | BindingFlags.Instance);

    method = method.MakeGenericMethod(T);

    return method.Invoke(context, null) as IQueryable;
}

and especially this line

MethodInfo method = typeof(myContext).GetMethod(nameof(myContext.Set), BindingFlags.Public | BindingFlags.Instance);

the stack trace is

   at System.RuntimeType.GetMethodImplCommon(String name, Int32 genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, Type[] types, ParameterModifier[] modifiers)
   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 Extensions.QueryableExtensions.Set(RetailContext context, Type T, Boolean dummy) in QueryableExtensions.cs:line 36

Where this Ambiguous error comes from?

like image 318
OrElse Avatar asked Oct 18 '25 11:10

OrElse


1 Answers

There are two overloads for the DbContext.Set method. You need to tell reflection which one.

https://learn.microsoft.com/en-us/dotnet/api/system.data.entity.dbcontext.set?view=entity-framework-5.0.0

E.g.

MethodInfo method = typeof(myContext).GetMethod(nameof(myContext.Set), Array.Empty<Type>());
MethodInfo method = typeof(myContext).GetMethod(nameof(myContext.Set), new Type[] { typeof(string) });

I removed the BindingFlags.Public | BindingFlags.Instance parameter as this is the default. If you were looking for a non public method you could use one of the overloads that includes it but I believe they require some other parameters as well.

A third options is to use the GetMethods call and then use linq to pick the correct one.

E.g.

typeof(myContext).GetMethods(/*Can add binding flags if needed*/).First(w => w.Name == nameof(myContext.Set) && w.GetParameters().Count() == 0 /* Or some other condition to disambiguate the function*/)
like image 177
groogiam Avatar answered Oct 21 '25 01:10

groogiam