What is  Lazy Loding?

As name implies, if we need to load parent data , it will load parent data without loading the related child  data.This is know as lazy loading

Otherwise, data is loaded only on demand (if required)

When to use ?

If we do not want to load the related entity at the same time as when the main entity is loaded/fetched, in this scenario we can use Lazy Loading.

Example :

Here we will see an example for lazy loading with the entity. Let we discuss with two tables, Here we having one table named as  customers which contain customerid,cusotmerName,CusomerMobileNo,customerdetailId ( it refer the primary key of Customerdetails table). then table Customerdetails which contain customerdetailId,customerAddress,Customercity….

var customerList = context.customers.Take(100);

foreach (var Customer in customerList)
{
// Login here
foreach (var CustomerDetail in customerList.Customerdetails)
{
// Login here
}
}

First line of code shows its is working as lazy, because it load only customers table without customerdetails table ( ie., without relations data).

Note :

From the above code, SQL hit will be high ( it will take 100 hits for fetching the customerdetails). Because every time the related data fetch will be happen inside the loop.


What is Eager Loading?

It Load all the related data with the loading object.

When to use ?

If we  want to load the related entity at the same time as when the main entity is loaded/fetched, in this scenario we can use Eager Loading.

Let we see the example for Eager Loading with the entity

var customerList = context.customers.Include(“Customerdetails”).Take(100);

foreach (var Customer in customerList)
{
// Login here
foreach (var CustomerDetail in customerList.Customerdetails)
{
// Login here
}
}

First line show it will fetch all the related entity for the customers table

Note :

Here SQL hit will be only one time , because it will fetch related entity using include keyword (first itself).