Important: I really don’t recommend doing this now, as there is a Nuget package that makes it all soooo much easier. Read more…
When you use Linq to create a query against an entity framework model, a common scenario is to use the .Include() extension method to make sure that any child objects are also loaded. This is mainly useful when the results of the query are to be sent over WCF, where the client is disconnected from the source of the query, and so cannot go back to the database to pick up any child objects as needed.
This works fine for simple queries, but falls apart when you want to do anything clever, like joins or shaping.
Without going into details, all you need to do is cast the query to an ObjectQuery<> and use .Include() on that. The syntax is not as obvious as it might be, so hereâ€™s an exampleâ€¦
ObjectQuery<Ferret> ferretQuery = ((from f in ctx.Ferrets select f) as ObjectQuery<Ferret>) .Include("User");
This particular example is too simple to require this trick, but I didnâ€™t want to distract from the syntax of the cast.
I got this trick (after a long time of frustrated scratching of head at some of Microsoftâ€™s more obscure and less helpful error messages) from this blog post.