我有一个 Expression<Func<Entity, string>>
可以是属性或嵌套属性访问器
y => y.SearchColumn
或
y => y.SubItem.SubColumn
我正在动态构建一个表达式树,并希望获得这样的 InvokeExpression
x => x.SearchColumn.Contains("foo");
x => x.Sub.SearchColumn.Contains("foo");
我很确定我可以打开表达式主体,然后部分应用 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;
}
编辑: Here is the full thing I'm trying to do along with the error
最佳答案
您需要做两件事 - 第一,您可以使用相同的 accessor.Body
,但它会引用不正确的参数,因为您创建了一个新参数。第二个你需要编写自定义 ExpressionVisitor
将所有原始 y
ParameterExpression
的用法替换为新创建的,因此结果表达式将被编译得很好.
如果您不需要创建新的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; }
}
PS:这个例子只有在原始查询中只有一个ParameterExpression
时才有效,否则访问者应该区分它们
更新
这是我的工作答案,您在更新中的完整示例 - https://dotnetfiddle.net/MXP7wE
关于c# - 如何重新包装 Linq 表达式树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32319453/