How to persuade a Linq query to include your child objects

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.

Be First to Comment

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.