用链式属性构造表达式树
本文关键字:表达式 属性 | 更新日期: 2023-09-27 18:16:04
我有一个方法,它接受Expression<Func<T, string>>
(例如x => x.Name
)和一个术语,并返回x => x.Name.Contains(term)
:
给定模型;
class X
{
public Y Y {get; set;}
}
class Y
{
public string Z {get; set;}
}
它适用于GenerateForMember<Y>(y => y.Z, "foobar")
,但目前不适用GenerateForMember<X>(x => x.Y.Z, "foobar")
。它给出了异常
'Z'不是'UserQuery+X'的成员
我如何更新我的方法与连锁属性工作?
方法如下:
protected Expression<Func<T, bool>> GenerateForMember<T>(Expression<Func<T,string>> expression, string term)
{
var type = typeof(T);
var memberExpression = ((expression.Body.NodeType == ExpressionType.Convert)
? ((UnaryExpression)expression.Body).Operand
: expression.Body) as MemberExpression;
ParameterExpression parameter = Expression.Parameter(type, type.Name.ToLower());
MemberExpression member = Expression.PropertyOrField(parameter, memberExpression.Member.Name);
var propertyInfo = memberExpression.Member as PropertyInfo;
var memberType = propertyInfo == null
? ((FieldInfo) memberExpression.Member).FieldType
: propertyInfo.PropertyType;
ConstantExpression constant = Expression.Constant(term, typeof(string));
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var containsMethodExp = Expression.Call(member, method, constant);
return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameter);
}
您正在剖析原始表达式,然后再重新构造它。这是不必要的。您可以直接使用expression.Body
来创建方法调用。像这样,它应该可以与任何lambda表达式一起工作。
var type = typeof(T);
ParameterExpression parameter = Expression.Parameter(type, type.Name.ToLower());
ConstantExpression constant = Expression.Constant(term, typeof(string));
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var containsMethodExp = Expression.Call(expression.Body, method, constant);
return Expression.Lambda<Func<T, bool>>(containsMethodExp, parameter);
试试这个:
protected Expression<Func<T, bool>> GenerateForMember<T>(Expression<Func<T, string>> expression, string term)
{
ConstantExpression constant = Expression.Constant(term, typeof(string));
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var containsMethodExp = Expression.Call(expression.Body, method, constant);
return Expression.Lambda<Func<T, bool>>(containsMethodExp, expression.Parameters[0]);
}