对于顶级IQueryable<T>(即不是查询表达式树的一部分),这可以通过自定义扩展方法接收匹配值、谓词表达式和表达式列表以及构建or 谓词来实现从他们。像这样的:
public static partial class QueryableExtensions
{
public static IQueryable<T> WhereAnyMatch<T, V>(this IQueryable<T> source,
V value, Expression<Func<V, V, bool>> match,
params Expression<Func<T, V>>[] itemsToMatch)
{
var parameter = Expression.Parameter(typeof(T), "e");
Expression<Func<V>> arg = () => value; // to let EF Core bind a parameter rather tnan a constant
var body = itemsToMatch
.Select(item => Expression.Invoke(match, Expression.Invoke(item, parameter), arg.Body))
.Aggregate<Expression>(Expression.OrElse);
var predicate = Expression.Lambda<Func<T, bool>>(body, parameter);
return source.Where(predicate);
}
}
您的案例的示例用法是:
.WhereAnyMatch(pattern, (item, arg) => EF.Functions.Like(item, arg),
e => e.Property1, e => e.Property2, e => e.Property3);
当然,一旦你有了那个方法,你可以添加其他的常用匹配谓词,例如Like:
public static partial class QueryableExtensions
{
public static IQueryable<T> WhereAnyLike<T>(this IQueryable<T> source,
string pattern, params Expression<Func<T, string>>[] itemsToMatch)
=> source.WhereAnyMatch(pattern, (item, arg) => EF.Functions.Like(item, arg), itemsToMatch);
}
示例代码将简化为
.WhereAnyLike(pattern, e => e.Property1, e => e.Property2, e => e.Property3);