这不起作用,因为Suffix method is specifically handled when visiting the field expression
if (methodCall.Method.Name == nameof(SuffixExtensions.Suffix) && methodCall.Arguments.Any())
{
VisitConstantOrVariable(methodCall, _stack);
var callingMember = new ReadOnlyCollection<Expression>(
new List<Expression> { { methodCall.Arguments.First() } }
);
Visit(callingMember);
return methodCall;
}
因此,需要调用像上面这样的扩展方法Suffix 才能开始,并且它必须至少有一个参数。您可能会想到提供一个默认值为“keyword”的可选参数会起作用,但表达式树不支持这一点,因此不会起作用。
另一种方法是在Expression<Func<T, object>> 上使用AppendSuffix 扩展方法来构建一些东西;最好的使用方法是将 lambda 表达式从 fluent 调用中提取出来并放入一个变量中
public static class NestHelperExtensions
{
public static Expression<Func<T, object>> KeywordSuffix<T>(this Expression<Func<T, object>> expression)
{
return expression.AppendSuffix("keyword");
}
}
var client = new ElasticClient();
Expression<Func<Person, object>> firstName = f => f.FirstName;
var searchResponse = client.Search<Person>(s => s
.Query(q => q
.Match(m => m
.Field(firstName.KeywordSuffix())
.Query("bar")
)
)
);
不太好的方法是将 lambda 表达式转换为 Expression<Func<T, object>> inline
var searchResponse = client.Search<Person>(s => s
.Query(q => q
.Match(m => m
.Field(((Expression<Func<Person, object>>)(f => f.FirstName)).KeywordSuffix())
.Query("bar")
)
)
);
另一种可能更简单的方法是为字符串"keyword" 引入一个常量,并在Suffix 扩展方法中使用它;它避免了到处使用字符串文字。