Best Practice For Loading Related Data in Asp.net Core Web API And EF.Core

asp.net-core asp.net-core-webapi entity-framework-core

Question

When to use Eager Loading or Explcit Loading in Asp.net Core Web API with EF Core? for example i wrote this query with Eager Loading.is this wrong? is should i Explicit Loading instead of Eager Loading?

  var plants = await _context.Plant.Include(plant => plant.Areas)
                                                 .ThenInclude(areas => areas.Units)
        .ToListAsync();

        return Ok(plants);
1
0
4/2/2020 9:21:24 AM

Accepted Answer

Well in most cases eager loading would be fine because in one round trip to database you fetch necessary data but consider following examples:

1- If you are going to show order list of specific customer and by click on each order, order lines should be listed, in this case lazy loading or explicit loading is better. you are not going to fetch all OrderLines until you need each one.

2- Don’t be eager to much, Take only what you’ll use:

var plants = await _context.Plant
                   .Where(some condition)
                   .Select(p => new PlantSummaryDto 
                   {
                       PlantId = p.Id,
                       PlantName = p.Name,
                       Areas = p.Areas.Select(a => new AreaSummaryDto 
                               {
                                    AreadId = a.Id,
                                    AreaName = a.Name,
                               })
                    .
                    .
                    .
                    }).ToListAsync();
1
4/2/2020 11:29:51 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow