public static IQueryable<TEntity>
QueryMany<TDbContext, TEntity, TOrder, TInclude>(TDbContext context, Expression<Func<TEntity, bool>> predicate,
Expression<Func<TEntity, TOrder>> order, bool ascending, Expression<Func<TEntity, TInclude>> include,
int skipCount, int takeMax)
where TEntity : class where TDbContext : DbContext
{
var query = context.Set<TEntity>().Where(predicate);
if (include != null)
query = query.Include(include);
if (skipCount > 0)
query = query.Skip(skipCount);
if (takeMax > 0)
query = query.Take(takeMax);
if (order != null)
query = ascending ? query.OrderBy(order) : query.OrderByDescending(order);
return query;
}
这使得可以使用任何搜索谓词(包括任何子属性集合)从任何上下文中的任何类型的集合中查询许多项,这些子属性集合具有按给定属性升序或降序排列的skip-and-take功能。可以为参数提供合适的“默认”值(例如,include和order为null,skip/take为零),以便有选择地启用这些功能位。
在我想包括main TEntity类型的两个子元素之前,这个方法很好地工作
. 我已经习惯了通常的多级include语法:
query.Include(parent => parent.Children.Select(child => child.Grandchildren)
但当然,泛型方法中的模板参数类型有效地将其固定到
我的问题是:有没有办法在我的泛型方法中提供更通用的include功能?提供任意的、多级别的include功能是很好的,但是到目前为止我还没有找到任何有效的方法。
更新:我知道也可以用字符串包含,但我对这种方法不感兴趣。我发现随着代码库的增长和发展,很难保持类型和字符串的可靠同步。请严格限制回答LINQ语句/方法语法。