Include using Lambda expression

Go To StackoverFlow.com

5

In a string based overload of Include we specify to include a collection and then a reference one level down simply by specifying relevant navigation properties in correct order:

query.Include("Level1Collection.Level2Reference");

But why when using an overload of Include that uses lambda expression, must we also use a Select statement to able to specify the above query:

query.Include(e => e.Level1Collection.Select(l1 => l1.Level2Reference)).

Why wouldn't the following work:

query.Include.(e => e.Level1Collection.Level2Reference)

thank you

2012-04-05 20:07
by user702769


7

Because the compiler doesn't recognize that the context has changed the meaning of the collection property from being a collection to being a stand-in for objects in the collection. And since the compiler doesn't change based on context, neither does intellisense.

When you feed Include a string statement, it knows it has to use reflection to know what properties to include anyway and there's no type-checking on compile. The underlying method knows that when it sees a dot after a collection property in the string that it should parse the properties of the objects within the collection for the next referenced property rather than the collection itself ("Level2Reference" in this case).

Or in other words: it's magic. :)

2012-04-05 20:28
by Jacob Proffitt
makes sense.Much appreciate - user702769 2012-04-05 20:39
Ads