How can I create an Expression tree that compares properties in a child object?
For example, I already can create a lambda expression tree that compares direct properties of an object. Like this:
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);
Which is (I believe) equivalent to:
entity => entity.JobNumber == "1005";
Where I am getting hung up is trying to figure out how to compare values in the properties of a child object. For example, given:
public class ParentObject
{
public ChildObject Child { get; set; }
// more properties of ParentObject
}
public class ChildObject
{
public string JobNumber { get; set; }
}
How would I build an expression that is the equivalent of:
parentEntity => parentEntity.Child.JobNumber == "1005"
Thanks for any help.
You just need to get the property of the returned property value:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With