我有一个Customer
课程,客户可以有多个Address
在我的存储库中,我有这个:
protected DbSet<T> Table;
和这个方法:
public T Find<TIncludeField>(Expression<Func<T, bool>> where,
Expression<Func<T, TIncludeField>> include)
=> Table.Where(@where).Include(include).FirstOrDefault();
然后我可以像这样使用它:
_customerRepo.Find(x => x.Reference.ToLower() == reference.ToLower(), x => x.Addresses);
我希望能够做到这一点:
public T Find<TIncludeField>(Expression<Func<T, bool>> where,
Expression<Func<T, ICollection<TIncludeField>>> includes)
=> Table.Where(@where).Include(includes).FirstOrDefault();
但我不知道如何在运行时创建.Include(includes)
有什么想法吗?
谢谢,
答案 0 :(得分:0)
您可以尝试此扩展方法
public static IQueryable<T> IncludesAll<TIncludeField>(this IQueryable<T> query,
IEnumerable<Expression<Func<T, TIncludeField>>> includes)
{
foreach (var include in includes)
{
query = query.Include(include);
}
return query;
}
答案 1 :(得分:0)
我建议使用这个(这将允许您包含不同类型的属性,而params数组允许您指定零,一个或多个包含)
public static IQueryable<T> IncludesAll<T>(this IQueryable<T> query,
params Expression<Func<T, object>>[] includes)
{
foreach (var include in includes)
{
query = query.Include(include);
}
return query;
}