【问题标题】:Best Practice For Loading Related Data in Asp.net Core Web API And EF.Core在 Asp.net Core Web API 和 EF.Core 中加载相关数据的最佳实践
【发布时间】:2020-07-14 05:21:51
【问题描述】:

何时在带有 EF Core 的 Asp.net Core Web API 中使用急切加载或显式加载? 例如,我使用 Eager Loading 编写了此查询。这是错误的吗?我应该显式加载而不是急切加载吗?

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

        return Ok(plants);

【问题讨论】:

    标签: asp.net-core entity-framework-core asp.net-core-webapi


    【解决方案1】:

    嗯,在大多数情况下,预先加载会很好,因为在一次往返数据库的过程中,您会获取必要的数据,但请考虑以下示例:

    1- 如果您要显示特定客户的订单列表并通过单击每个订单,应列出订单行,在这种情况下延迟加载或显式加载更好。在需要每个 OrderLine 之前,您不会获取所有 OrderLine。

    2- 不要急于求成,只拿你会用到的:

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 1970-01-01
      • 2012-05-30
      • 2020-06-16
      • 1970-01-01
      • 2021-05-03
      相关资源
      最近更新 更多