C# Expression Tree Parameter for Parent Navigation Property

c# entity-framework expression-trees lambda

Question

How can I create a ParameterExpression for the parent side of a 1 to * Navigation Property?

The following works for the child entity:

var parameter = Expression.Parameter(
    typeof(T), // where T is the entity type
    GetParameterName()); // helper method to get alias

Trying something similar on TParent produces a query originating at the Context, and not as a property on the child.

The lambda equivalent would be like this:

var q = from f in context.Foo 
        where f.Bar.BarId == 1...
         // where bar is the Navigation Property to the parent

Edit for clarity:

I use the following to create a member expression from a property:

Expression exp = Expression.Equal(
    Expression.Property(parameter, "SomeColumn"),
    Expression.Constant("SomeValue"));

So it looks like I should be using MemberExpression instead of ParameterExpression for this case.

Expert Answer

I'm a little confused... ".Bar" isn't a ParameterExpression - it is a MemberExpression. f is the parameter. What exactly is it that you want to do?

Note that one option is to load the sample code into reflector, turn of the .NET 3.5 hints, and read how it does it - it'll look like the code here, but is usually easy enough to follow.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why