Eager Loading entities in Entity Framework
As I am starting to move forward with entity framework on all my projects, I am discovering new ways of writing queries that works with entity framework as compared to in the past with Linq To SQL.
In entity framework, if an entity has another entity or child collections based on 1 to 1 mapping or 1 to many or many to many mapping, by default those associations do not get loaded. Everything in entity framework has to be explicit. If you want to load a specific entity or entity set, you have to explicitly tell entity framework by calling Include method passing in the name of the association or navigation property that you want loaded. Below is an example that shows eagerly loading 1 to many relationship Orders for a customer.
In the above code, I am using Include method,passing in the name of the association property that I want loaded immediately when I am retrieving a customer. Include method is pretty flexible if you want to load hierarchy any level deep. For example if I have a customer and I want to load Customer, its Orders and also the OrderDetails for those orders, you dont have to make separate include calls for loading Orders and OrderDetails. Simply traversing the hierarchy inside the include method would cause the both entities to be immediately loaded with the customer. Also there is no limitation on the number of times you can call Include with an object query. so you can basically load a many to many entity along with two 1 to many relationships. Below is an example that demonstrates the usage.
In the above example, I am eagerly loading 3 entities. First I am traversing the hierarchy for Order and OrderDetails to load both entities immediately. I am also calling Include again to load CustomerDemographics entities which happens to be a many to many relationship.