Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHakim Rachidi
38,490 PointsInclude()? Why?
Why do I have to explicitly include properties with in the selected object? I tired out dropping the Includes and every still works fine. So why is there this method and when do I have to use it?
1 Answer
Hakim Rachidi
38,490 PointsSystem.Data.Entity
@Simon Coates In the sql query EF performs a JOIN on the foreign and the primary key of the target table. This means without calling Include with the used child properties which are interally located in another table .NET is throwing a null ref exception because I am targeting a column that is not located on this table;
Simon Coates
28,694 PointsI think you can get oddities if the data is already tracked. (when only some of your data needs the sql query).
Simon Coates
28,694 PointsSimon Coates
28,694 PointsFor starters, i think you can avoid this stuff if you use 'lazy loading' (where nav properties are marked as 'virtual'). I think it's covered later in the course (the downside, i think, is performance overhead). Using Include can seem a little unpredictable. I think sometimes code without includes crashes or passes depending on whether the data is already being tracked by the context. However, I think the suggestion is to use Include or Select to indicate what you're interested in. I had wished James Churchill had explained this further. I've watched this video multiple times and I still don't know what the rules are ("Use select when...", "Use Include when").