Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing against child property in generic/dynamic linq predicate with reflection

I am having to generically build a comparative predicate for an Entity Framework Linq query. I'm using reflection and am able to build a single level Lambda expression without any trouble. However where I am starting to get stuck is I have an Entity that has a relationship

public class Parent {
    public virtual Child child { get; set; }
    .... Other Stuff...
}

public class Child {
    public int property { get; set; }
    public virtual Parent parent { get; set; }
    .... Other Stuff.....
}

How can I can I pass in "Child.property" into Reflection to be able to create a lambda expression comparing and come up with a lambda expression similar to item => item.Child.property == value?

like image 912
UnHoly Ram Avatar asked Jan 28 '26 09:01

UnHoly Ram


1 Answers

I think you are looking for this:

ParameterExpression parameter = Expression.Parameter(typeof(Parent), "item");
Expression child = Expression.PropertyOrField(parameter, "child");
Expression childProperty = Expression.PropertyOrField(child, "property");
int value = 1;
Expression comparison = Expression.Equal(childProperty, Expression.Constant(value));

Expression<Func<Parent, bool>> lambda = Expression.Lambda<Func<Parent, bool>>(comparison, parameter);


var sample = new[] { new Parent() { child = new Child() { property = 1 } } };
var result = sample.Where(lambda.Compile());
like image 72
Aducci Avatar answered Jan 30 '26 04:01

Aducci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!