Entity framework loading options
LazyLoading, default option
Lazyloading means that only all primairy entities are returned by the query. Related entities are loaded at the moment a navigation property is accessed. A navigation property in the example ( under ) is the Adresses ICollection. At the moment you access the Addresses ICollection entity framework executes a query to load the needed data.
If you don't want this behaviour you can simply disable lazy loading by removing the virtual keyword at the ICollection. The other option is to disable lazy loading for the whole context by override the modelcreated method and disable lazyloading. A third option is to disable layz loading via the configuration property of the DbContext
// get the customer [Table("Customers")] public class Customer { // propertys public int CustomerId { get; set; } public string Name { get; set; } public int KlantNumber { get; set; } // navigation public virtual ICollection< Address> Addresses { get; set; } } [Table("Address")] public class Address { // propertys public int AddressId { get; set; } public int CustomerId { get; set; } public string Street { get; set; } public string Postalcode { get; set; } public string City { get; set; } }
Eager loading
Eager loading is another loading option. Allthough it's not realy an option. Eager loading can be enabled at method level by using the include keyword:
List klanten = db.Klanten.Include("Adres").ToList();
A query for all customers ( klanten ) and their adress already included.
Explicit loading
When you have disabled lazy loading for the whole context but detect that you want to use it for one property, that's excplicit loading: Explicit loading is done by using the load keyword:
// get the customer var klant = db.klanten.find(10); // excplicit load adress db.entry(klant).Reference( a => a.Adress).load();