I have the below model. What is the better way to load the parent entity with child entity at the time of fetching from the DB with find method?
Parent Entity:>
As you said:
Notes: As of now, if I used the Include(i => i.Address) then, and then, only I am able to load the child entity.
Yes! this is the best way to load related data in EF Core.
You further said:
I already use the Include but is there any other option exist to load child entity if I get the parent entity.
Yes! There is! That is called Lazy loading. To enable lazy loading you have to make the navigation property virtual as follows:
public class Client
{
public int Id { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public DateTime DateOfBirth { get; set; }
public virtual Address Address { get; set; } // <-- Here it is
}
And you have to register your DbConext
as follows:
services.AddDbContext(
b => b.UseLazyLoadingProxies() // <-- Here is it is
.UseSqlServer(myConnectionString));
UseLazyLoadingProxies()
method is available in the Microsoft.EntityFrameworkCore.Proxies nuget package.
Note: You cannot disable lazy loading for a certain query. So using Eager loading is the best way to load related data in EF Core.