.NET 6.0 中使用 DbContext 发现不明确的匹配

Cam*_*est 2 .net c# entity-framework-core

执行此代码时,当使用 Entity Framework Core 6.0.3 以 .NET 6.0 为目标时,我收到“发现不明确的匹配”。

context.GetType().GetMethod("Set")
Run Code Online (Sandbox Code Playgroud)

它发生在我的所有模型类型上,并且我尝试过 EF Core 6.0.2 和 6.0.0。

使用.NET Core 3.1,同样的代码没有问题。

还有其他人得到这个吗?

Cam*_*est 8

当您只有所需 DbSet 的 Type 实例时,请使用 GetMethod (string name, int genericParameterCount, Type[] types) 的重载。

例子:

Type t = [type of DbSet you need]

var results = context.GetType()
                     .GetMethod("Set", 1, Type.EmptyTypes)
                     .MakeGenericMethod(t)
                     .Invoke(context, null);
Run Code Online (Sandbox Code Playgroud)

这将调用 DbContext 的 Set 方法,该方法不带任何参数,但需要一个 genericParameter。