类型或方法有 3 个泛型参数,但提供了 2 个泛型参数

本文关键字:参数 泛型 方法 类型 | 更新日期: 2023-09-27 17:56:17

我有以下工作代码:

Context context = new Context(_options);
Expression<Func<Context.Person, Context.Address>> e1 = x => x.Address;
Expression<Func<Context.Address, Context.Country>> e2 = x => x.Country;
IIncludableQueryable<Context.Person, Context.Address> a = context.Persons.Include(e1);
IIncludableQueryable<Context.Person, Context.Country> b = a.ThenInclude(e2);
List<Context.Person> result = context.Persons.Include(e1).ThenInclude(e2).ToList();
其中"包含"

和"然后包含"是实体框架核心扩展方法。

在我的代码中,我需要使用泛型类型,所以我使用反射:

IQueryable<Context.Person> persons = context.Persons;
MethodInfo include = typeof(EntityFrameworkQueryableExtensions).GetMethods().First(x => x.Name == "Include" && x.GetParameters().Select(y => y.ParameterType.GetGenericTypeDefinition()).SequenceEqual(new[] { typeof(IQueryable<>), typeof(Expression<>) }));
MethodInfo thenInclude = typeof(EntityFrameworkQueryableExtensions).GetMethods().First(x => x.Name == "ThenInclude" && x.GetParameters().Select(y => y.ParameterType.GetGenericTypeDefinition()).SequenceEqual(new[] { typeof(IIncludableQueryable<,>), typeof(Expression<>) }));
Expression<Func<Context.Person, Context.Address>> l1 = x => x.Address;
Expression<Func<Context.Address, Context.Country>> l2 = x => x.Country;

try {
  MethodInfo includeInfo = include.MakeGenericMethod(typeof(Context.Person), l1.ReturnType);
  IIncludableQueryable<Context.Person, Context.Address> r1 = (IIncludableQueryable<Context.Person, Context.Address>)includeInfo.Invoke(null, new Object[] { persons, l1 });
  MethodInfo thenIncludeInfo = thenInclude.MakeGenericMethod(typeof(Context.Address), l2.ReturnType);
  IIncludableQueryable<Context.Address, Context.Country> r2 = (IIncludableQueryable<Context.Address, Context.Country>)thenIncludeInfo.Invoke(null, new Object[] { r1, l2 });
  var r = r2.AsQueryable();
} catch (Exception ex) { }

但是在此代码行上:

MethodInfo thenIncludeInfo = thenInclude.MakeGenericMethod(typeof(Context.Address), l2.ReturnType);

我收到以下错误:

The type or method has 3 generic parameter(s), but 2 generic argument(s) were provided. A generic argument must be provided for each generic parameter.

我可以通过查看 ThenInclude 定义来理解错误,但我不确定如何解决它......

类型或方法有 3 个泛型参数,但提供了 2 个泛型参数

正如消息所暗示的,ThenInclude需要 3 个类型参数:TEntity, TPreviousProperty, TProperty .从您的代码来看,这似乎可行:

MethodInfo thenIncludeInfo = thenInclude.MakeGenericMethod(
    typeof(Context.Person), typeof(Context.Address), l2.ReturnType);