Geo*_*uer 6 c# linq expression metaprogramming expression-trees
我有一个Expression<Func<Entity, string>>可以是属性或嵌套属性访问器
y => y.SearchColumn
Run Code Online (Sandbox Code Playgroud)
要么
y => y.SubItem.SubColumn
Run Code Online (Sandbox Code Playgroud)
我正在动态构建一个表达式树,并希望像这样得到一个InvokeExpression
x => x.SearchColumn.Contains("foo");
x => x.Sub.SearchColumn.Contains("foo");
Run Code Online (Sandbox Code Playgroud)
我敢肯定,我可以解开表达身体,然后部分应用X ParameterExpression到它,但我想不通的神奇咒语,使这种情况发生
所以我有类似的东西
Expression<Func<Entity, string>> createContains(Expression<Func<Entity, string>> accessor) {
var stringContains = typeof(String).GetMethod("Contains", new [] { typeof(String) });
var pe = Expression.Parameter(typeof(T), "__x4326");
return Expression.Lambda<Func<Entity, bool>>(
Expression.Call(
curryExpression(accessor.Body, pe),
stringContains,
Expression.Constant("foo")
)
, pe
);
}
static Expression curryExpression(Expression from, ParameterExpression parameter) {
// this doesn't handle the sub-property scenario
return Expression.Property(parameter, ((MemberExpression) from).Member.Name);
//I thought this would work but it does not
//return Expression.Lambda<Func<Entity,string>>(from, parameter).Body;
}
Run Code Online (Sandbox Code Playgroud)
您需要做两件事 - 第一件事您可以使用相同的参数accessor.Body,但当您创建新参数时,它将引用错误的参数。第二个,您需要编写自定义ExpressionVisitor,将原始的所有用法替换y ParameterExpression为新创建的,因此结果表达式将被很好地编译。
如果您不需要创建 new ParameterExpression,那么您可以只使用相同的accessor.Body并将原始数据重新ParameterExpression发送到新树。
所以这是我的测试工作副本与新的ParameterExpression- https://dotnetfiddle.net/uuPVAl
以及代码本身
public class Program
{
public static void Main(string[] args)
{
Expression<Func<Entity, string>> parent = (y) => y.SearchColumn;
Expression<Func<Entity, string>> sub = (y) => y.Sub.SearchColumn;
var result = Wrap(parent);
Console.WriteLine(result);
result.Compile();
result = Wrap(sub);
Console.WriteLine(result);
result.Compile();
result = Wrap<Entity>((y) => y.Sub.Sub.Sub.SearchColumn);
Console.WriteLine(result);
result.Compile();
}
private static Expression<Func<T, bool>> Wrap<T>(Expression<Func<T, string>> accessor)
{
var stringContains = typeof (String).GetMethod("Contains", new[] {typeof (String)});
var pe = Expression.Parameter(typeof (T), "__x4326");
var newBody = new ParameterReplacer(pe).Visit(accessor.Body);
var call = Expression.Call(
newBody,
stringContains,
Expression.Constant("foo")
);
return Expression.Lambda<Func<T, bool>>(call, pe);
}
}
public class ParameterReplacer : ExpressionVisitor
{
private ParameterExpression _target;
public ParameterReplacer(ParameterExpression target)
{
_target = target;
}
protected override Expression VisitParameter(ParameterExpression node)
{
// here we are replacing original to a new one
return _target;
}
}
public class Entity
{
public string SearchColumn { get; set; }
public Entity Sub { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
PS:此示例仅在原始查询中只有一个的情况下才有效ParameterExpression,否则访问者应区分它们
更新
这是我的工作答案以及更新中的完整示例 - https://dotnetfiddle.net/MXP7wE