Hi @usha, Welcome to Microsoft Q&A.
Here's a simple example:
Configure entity relationships: In your entity classes, you can configure navigation properties to enable lazy loading. For example, if you have a Blog class and a Post class, you can implement lazy loading by configuring the Posts property of the Blog class.
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
Configure in DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.HasMany(b => b.Posts)
.WithOne()
.HasForeignKey(p => p.BlogId);
}
Use virtual keyword: Using virtual keyword on navigation properties is a key step to enable lazy loading. This tells EF Core to generate proxy classes at runtime to perform lazy loading when navigation properties are accessed.
public virtual ICollection<Post> Posts { get; set; }
Enable lazy loading: In some cases, EF Core may have lazy loading enabled by default. Make sure your query is not using the AsNoTracking method as it turns off lazy loading.
var blogs = dbContext.Blogs.ToList();
Note that lazy loading may cause an extra query to be executed for each related entity when the main entity is loaded. To solve this problem, you can use the Include method or use explicit loading if needed.
Enabling lazy loading globally may cause some performance issues, as it may cause multiple additional database queries to be triggered when accessing navigation properties. Therefore, when enabling lazy loading, monitor performance and use it with caution to ensure you do not cause performance degradation. In some cases, eager loading (Eager Loading) may be a better choice because it can reduce the number of queries by loading related data immediately at query time.
In summary, the specific choice depends on your application needs and performance requirements.
Best Regards,
Wenbin
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.