In this post let’s see how we can access nested properties in Expression Trees. In one of my previous posts, I wrote about Writing a Very Basic Dynamic Query using Expression Trees. There I wrote a expression tree which accesses the first level properties of a class. And today I am going to write a expression tree which accesses the nested properties of a class.
Let’s consider the following scenario. I have two classes named “Employee” and “Department”. Employee is belonging to a department. I can model the relationship as follows.
Now how we can we write the same in using expression trees. Let’s find out.
First step is to create the expression tree that represents the parameter to the predicate which is “e”.
Now comes the place where we need to access the nested property.
In above two lines, first line is for accessing the Department property of the Employee. Then in the second line I am accessing the property DepartmentId and note that what I have passed as the first parameter of Expression.Property() method. It’s the Department property of the Employee. So what means here is I am accessing the DepartmentId property of the Department. Now you must be getting how it works, by following the above approach, we can access any property in any level.
Then it’s pretty much a simple task ahead. We have to compose the right side of the expression, compile the expression tree into executable code and finally pass it to Where extension method. For that I am writing the following.
And this is the output when I foreach on “employees”.