Related entities are automatically loaded from the data source when you access a navigation property. With this type of loading, be aware that each navigation property that you access results in a separate query executing against the data source if the entity is not already in the ObjectContext. Here is a lazy loading enabled example
db.Configuration.LazyLoadingEnabled = true;// enable lazy loading
var student = db.Students.FirstOrDefault(st => st.PersonID == 1);// first queri will execute here
int i=student.Enrollments.Count;// Second query will execute here to load selected students enrolments
It will execute two separate queries to the server. First is to get student's sealer properties and second query is to load his enrollments.
In this type only one single request will go to the database. It will return all entities defined by the path in a single result set. You can specify the related data that you want to load with the query by specifying paths.
db.Configuration.LazyLoadingEnabled = false;
var student = db.Students.Include("Enrollments").FirstOrDefault(st => st.PersonID == 1);
this will execute one query to load student's scaler properties and his navigational property(Collection of Enrollments).
How to choose the best method
You need to consider three things,
- How many connections that you are going to make with the database. If you are using lazy loading there will be a database call for all the reference points of a navigation properties if referred navigation property is not in the context.
- How much data that you are going to retrieve from databaseIf you choose to load all the data in initial query with differed loading it will be too slow when you have huge amount of data to retrieve.
- Complexity of the query . When you are using lazy loading the queries will be simple because all the data is not loaded in the initial query. If you use immediate loading it will make quires will be more complex with query paths