我如何保留一个lambda表达式的引用,该表达式稍后将传递给OrderBy或LoadWith函数?

我正在尝试创建一个访问数据库的通用方法。 这将意味着以下参数:页面索引,每页显示的项目数,订购选项,加载选项等。

... public IQuerable GetAll(int pageIndex, int itemsToDisplayPerPage, System.Linq.Expressions.Expression<Func>[] orderBy, System.Linq.Expressions.Expression<Func>[] loadOptions) { DataContext dc = null; IQuerable result = null; // Make some initalizations ... foreach(var item in orderBy) { result = result.OrderBy(item); } System.Data.Linq.DataLoadOptions loadOptions = new System.Data.Linq.DataLoadOptions(); foreach(var item in loadOptions) { loadOptions.LoadWith(item); } ... } ... 

问题是System.Linq.Expressions.Expression< Func >类型不是将为上述两个示例传递的任何lambda表达式的良好通用表示。

订购会因为对订单没有任何意义的对象类型而崩溃。 另外在loadWith上也行不通。 所以我不知道如何处理这个问题。 有什么建议? 谢谢。

不确定LoadWith,因为我们使用linq实体,但我们成功地获得了orderby在存储库Get方法中工作。 客户端代码如下所示:

 var results = _repository.GetAll( new GetAllCriteria() .OrderBy(x => x.Property1) .OrderBy(x => x.Property2) ); 

我们还没有在存储库方法中使用generics,这可能会出现在未来的重构中。 但标准实现如下:

 public class GetAllCriteria { public Dictionary>, bool> ToBeOrderedBy { get; private set; } public GetAllCriteria OrderBy( Expression> expression) { return OrderBy(expression, true); } public GetAllCriteria OrderByDescending( Expression> expression) { return OrderBy(expression, false); } private GetAllCriteria OrderBy( Expression> expression, bool isAscending) { if (expression != null) { if (ToBeOrderedBy == null) ToBeOrderedBy = new Dictionary>, bool>(); ToBeOrderedBy.Add(expression, isAscending); } return this; } } 

然后,存储库命令如下:

 public Collection GetAll(GetAllCriteria criteria) { var query = dbContext.CustomTypes.AsQueryable(); // some code // apply order by if (criteria.ToBeOrderedBy != null && criteria.ToBeOrderedBy.Count > 0) { var firstOrderBy = criteria.ToBeOrderedBy.First(); query = firstOrderBy.Value ? query.OrderBy(firstOrderBy.Key) : query.OrderByDescending(firstOrderBy.Key); query = criteria.ToBeOrderedBy.Skip(1).Aggregate(query, (lastOrderBy, nextOrderBy) => nextOrderBy.Value ? ((IOrderedQueryable)lastOrderBy) .ThenBy(nextOrderBy.Key) : ((IOrderedQueryable)lastOrderBy) .ThenByDescending(nextOrderBy.Key)); } // some more code var results = query.ToList(); return results; } 

如果这适用于linq到实体,我会想象它应该与linq一起使用到sql。