【问题标题】:Ambiguous match found exception模棱两可的匹配发现异常
【发布时间】:2022-08-04 10:29:55
【问题描述】:

好吧,在从 net core 3.1 升级到 .NET 5 之前,这个曾经很好用

产生错误的扩展方法是

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

尤其是这条线

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

堆栈跟踪是

   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

这个模棱两可的错误来自哪里?

  • 不够,咳咳,上下文。例如。什么是myContext.Set(它是如何声明的)?
  • 请共享足够的代码,并且您的堆栈跟踪也不完整。
  • 不回答您的问题,但您应该迁移到 net6,因为 net5 已经 EOL dotnet.microsoft.com/en-us/platform/support/policy/dotnet-core
  • 听起来有不止一种方法具有该名称。 Set 是否过载?

标签: c# asp.net-core .net-core .net-5 .net-core-3.1


【解决方案1】:

DbContext.Set 方法有两个重载。你需要告诉反射是哪一个。

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

例如。

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

我删除了 BindingFlags.Public | BindingFlags.Instance 参数,因为这是默认值。如果您正在寻找一种非公共方法,您可以使用包含它的重载之一,但我相信它们也需要一些其他参数。

第三种选择是使用 GetMethods 调用,然后使用 linq 选择正确的方法。

例如。

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*/)

【讨论】:

    猜你喜欢
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多