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

时间:2016-07-10 18:11:45

标签: c# entity-framework entity-framework-core

我有以下工作代码:

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();

其中IncludeThenInclude是实体框架核心扩展方法。

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

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定义来理解错误,但我不确定如何解决它...

1 个答案:

答案 0 :(得分:3)

如消息所示,ThenInclude需要3个类型参数:TEntity, TPreviousProperty, TProperty。从您的代码中,它似乎会起作用:

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