如何创建比较子对象中属性的表达式树?
例如,我已经可以创建一个lambda表达式树来比较对象的直接属性。像这样:
var propertyName = "JobNumber";
var propertyValue = "1005";
Type entityType = typeof(ParentObject);
OperatorDelegate comparisonMethod = Expression.Equal;
var parameter = Expression.Parameter(entityType, "entity");
var lambda =
Expression.Lambda<Func<ParentObject, bool>>(
comparisonMethod(Expression.Property(parameter, propertyName), Expression.Constant(propertyValue)),
parameter);
这是(我相信)相当于:
entity => entity.JobNumber == "1005";
我挂断的地方是试图找出如何比较子对象属性中的值。例如,给定:
public class ParentObject
{
public ChildObject Child { get; set; }
// more properties of ParentObject
}
public class ChildObject
{
public string JobNumber { get; set; }
}
我如何构建一个等同于:
的表达式parentEntity => parentEntity.Child.JobNumber == "1005"
感谢您的帮助。
答案 0 :(得分:14)
您只需要获取返回的属性值的属性:
var child = Expression.Property(parameter, "Child");
var jobNumber = Expression.Property(child, propertyName);
var lambda =
Expression.Lambda<Func<ParentObject, bool>>(
comparisonMethod(jobNumber, Expression.Constant(propertyValue)),
parameter);