IT:AD:EF:HowTo:Include Related Entities in Queries
Lazy Loading
Lazy loading was turned on by default in EF40.
Lazy loading can be turned off:
myObjectContext.ContextOptions.LazyLoadingEnabled=false;
Explicit Loading
Explicit loading can be done using Include method, and the autogenerated xxxReference property:
context.Contacts.Include("Addresses");
Since EF 4.1, one can include using Linq as follows:
var princesses1 = context.Princesses
.Include(p => p.Unicorns)
.ToList();
Explicit loading can be done using Include and a query path.
This will bring in Orders, OrderDetails, and Addresses:
context.Contacts.Include("Orders.OrderDetails").Include("Addresses");
Note:
MS warns against Query Paths as they become hard to predict outcome.
- Note that Included data cannot be sorted/Filtered. You can't say Include the Contact's Addresses, but only those in NZ.
- Pros and cons are, Lazy Loading can hit the db many times. Load() can allow you to inspect the Db before invoking a secondary Load, and Include hits the db only once, but doesn't give you the ability to check first.
Explicit Loading, afterwards
If the first query has been completed, you can explicity get related data…
Explicit loading loading using Load method can be used effectively:
//Load sub collection now of entity already loaded: contact.AddressesReference.Load();