首页 > 解决方案 > Entity Framework Core 使用包含而不加载所有数据

问题描述

这是我的查询

var geometrias = _context.Geometrias
                    .Include(g => g.GeometriaRegistos)
                    .Include(g => g.Matriz)
                    .ThenInclude(m => m.Referencia)
                    .Where(g => g.Matriz.ReferenciaId == referenciaId && !g.IsDeleted && !g.Matriz.IsDeleted)
                    .OrderByDescending(g => g.Id)
                    .Take(20)
                    .ToList();

我想每个 Geometria 只获得 20 个 GeometriaRegistos

.Include(g => g.GeometriaRegistos.Take(20))

不工作

这是模型

public class GeometriaRegisto
{
    public int Id { get; set; }

    public float X1 { get; set; }
    public float X2 { get; set; }
    public float X3 { get; set; }
    public float X4 { get; set; }

    public int GeometriaId { get; set; }
    public Geometria Geometria { get; set; }

    public int ProducaoRegistoId { get; set; }
    public ProducaoRegisto ProducaoRegisto { get; set; }
}

public class Geometria
{
    public int Id { get; set; }

    public string Componente { get; set; }

    public bool IsDeleted { get; set; }

    public int MatrizId { get; set; }
    public Matriz Matriz { get; set; }

    public ICollection<GeometriaRegisto> GeometriaRegistos { get; set; }
}

我曾经使用 Dapper 和 SQL 存储过程来做到这一点,我正在尝试使用 linq 来管理它,但我找不到一种方法来做到这一点,而不必先将它们全部加载到内存中然后再次过滤,但它很多数据

标签: c#entity-framework-core

解决方案


不幸的是,不支持这种情况。

当你.Include实际上是在暗示你渴望这段JOIN关系时。

为了实现您的愿望,我建议您在Geometrias不包括GeometriasRegistros. 然后选择您将要获取的 id grIds = geometrias.Select(g=>g.GeometriasRegistros.Take(20).Id).Distinct()。下一步是根据这些 Id 进行查询并包装它,只需手动填充您的集合...

不是艺术品,但会起作用


推荐阅读