【发布时间】:2016-07-11 02:32:46
【问题描述】:
我有以下工作代码:
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();
Include 和 ThenInclude 是 Entity Framework Core 扩展方法。
在我的代码中,我需要使用泛型类型,所以我使用反射:
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 定义来理解错误,但我不确定如何解决它......
【问题讨论】:
-
ThenInclude的签名需要 3 个通用参数 (<TEntity, TPreviousProperty, TProperty>) 但您只传递了 2 个。 -
@haim770 我试图通过 3 使用“MethodInfo thenIncludeInfo = thenInclude.MakeGenericMethod(typeof(Context.Person), typeof(Context.Address), l2.ReturnType);”但随后我收到错误“'Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions+IncludableQueryable2[Person,Address]”类型的对象无法转换为“Microsoft.EntityFrameworkCore.Query.IIncludableQueryable2[Person,System.Collections.Generic”类型。 ICollection`1[地址]]'。”。你知道为什么吗?
标签: c# entity-framework entity-framework-core