What the heck does Include do!?!?
So we’re currently on week… 8? Of our SDG-Proforma cohort, and the last week or so we’ve been working with databases. At the same time, I’ve been tearing my hair out trying to understand one thing:
Linq includes.
As my coworkers and instructors can attest, include for some reason had me absolutely stumped. So many things were happening and it seemed that there were so many gotchas that it made no sense whatsoever, but finally, FINALLY I think I have a decent grasp on it.
So, for the rest of this post I’ll be going over what I’ve learned. Sound good? Great. We’re doing this!
Since we’re good little developers, we’ll start at the documentation like all good developers do. A quick search gives us:
ObjectQuery<T>.Include Method
Specifies the related objects to include in the query results.
Okay, what does this mean?
Get Christopher Tiller’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s say for instance I had a SQL database of people. In this database we’ll say that we have three tables. These tables are going to be called People, Banks, and Addresses. People and Banks have a many-many relation, and Addresses have a many-many relation with people.
Normally, if I were to do a query on people, but wanted data from any of the other tables, I would have to do a where, or a first, or any sort of method that returns an implicit join. With Include, however, I can explicitly say that “hey, I want to include Banks and Addresses in the query results”, like so:
Var query = context.People.Include(i => i.Addresses).include(I => i.Banks);And then query would have a reference to both addresses and banks inside of the query. I could then do operations that involve both.
Essentially, it is the same as doing a SQL JOIN statement on the ID of each. In SQL, it would look something like:
SELECT *
FROM People
JOIN People ON PeopleAddresses.ID = People.ID
JOIN PeopleAddresses ON Addresses.ID = PeopleAddresses.ID
JOIN People ON PeopleBanks.ID = People.ID
JOIN PeopleBanks ON Banks.ID = PeopleBanks.IDOr something roughly to that effect.
As you can see, it saves us quite a bit of work, and since we’re explicitly saying what we’re querying, we get a bit of a performance boost.
As a final bit of information, a slight gotcha. Since we’re doing many-many relationships if we tried to do something like: query.people.addresses we’d have some issues, mostly because it’s pulling the entire list instead of just a single item, so in order to work with the data you need to make sure you run a foreach, first, or select statement to get a single item.
And that’s it! Hope you enjoyed, and hope it was helpful!





