
Explicit loading is a way in which related data is explicitly loaded from database.You can disable lazyloading in entity framework core.After turning lazy loading off,you can still load entities by explicit loading by load method of related entities.
this.Configuration.LazyLoadingEnabled=false;
How to implement Explicit Loading
To implement explicit loading , you can use "Entry" method of the DBContext class along with the "Collection" or "Reference" methods to explicitly load related entities.
public class Busdetails
{
public int busid{get;set;}
public string busfrom{get;set;}
public string busto{get;set;}
public date journeydate{get;set;}
public string busname{get;set;}
public string boardingpoint{get;set;}
public string destinationpoint{get;set;}
public virtual Icollection<BusFeatures> BusFeatures{get;set;}
}
public class BusFeatures
{
public int busfid{get;set;}
public string busfeature{get;set;}
public int busid{get;set;}
public virtual Busdetails{get;set;}
}
In above code,Each bus has different or multiple features like ChargePoint,WaterBottle,Bedsheet,Pillow,Toilet etc.But these features will be available for specific bus only.For example, some buses will not have Toilet facility.One bus has many features ,so it is one to Many relationship.
public class AppDbContext:DBContext
{
public DBSet<Busdetails>{get;set;}
public DBSet<BusFeatures>{get;set;}
}
In the below scenario,it retrieves list of busdetails,Here busdetails is parent entity and busfeatures is reference entity.
using (var context=new AppDBContext())
{
var fullbusdetails=context.busdetails.ToList(); //retrieves full bus details
foreach(var features in fullbusdetails)
{
context.Entry(features).Reference(f=>f.busfeatures).Load();
console.writeline($"Bus name{features.busname}")
console.writeline($"Bus Feature{features.busfeature}")
}
}
Reference or Collection Method: if you want to explicitly load a related single entity(one to one or many to one relationship),you can use Reference method else you can use
Collection method.
Advantages of Explicit Loading:-
Improved Performance:-
It allows you to load related entities on demand,so that only specific data can be loaded from database.
Reduces Memory Usage:-
it selectively loads related entities when needed,you can conserve memory resources.