我正在尝试重构通用存储库的一些代码,该存储库传入一个过滤器对象,该过滤器对象将过滤数据以及页面、排序等。
各传承Filter
(例如 CustomerFilter)可以选择定义自己的表达式过滤器,该过滤器将由存储库中的基类应用。
因此客户过滤器将具有如下属性:
public string CustomerId { get; set; }
public override Expression<Func<object, bool>> Predicate => c => ((Customer)c).Id == CustomerId;
然后存储库将运行存储库中的过滤器,有点像这样(它还不是通用的!):
using (var context = new CustomerContext())
{
return await Filter<Domain.Customer>.ApplyAsync(filter, context.Customers.AsQueryable()).ConfigureAwait(false);
}
这工作正常,但我需要一种方法来为更复杂的示例以更好的方式构建表达式。
例如,过滤器可能允许根据状态过滤客户,但前提是已设置。
public string CustomerId { get; set; }
public State? CustomerState { get; set; }
public override Expression<Func<object, bool>> Predicate => c => (((Customer)c).Id == CustomerId) && (((Customer)c).State == CustomerState ?? (Customer)c).State);
这不仅变得一团糟,而且还有很多不必要的转换和括号。所以我想做的是 getter 中的表达式构建器,它将以更清晰的方式构建表达式,例如if(State != null) { CustomerState == State; }
。但这就是我不确定如何继续的地方,所以如果有人可以帮助我,我将不胜感激。