.NET Core:如何在 dto 中合并嵌套的一对多关系

.NET Core: How to merge nested one-to-many relations in dto

如何合并父实体中的嵌套子实体?

我有这三个实体:

public class Faculty
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<Group> Groups { get; set; }
}

public class Group
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public ICollection<User> Users { get; set; }
}

public class User
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

ResultDto 的预期结果是:

public class ResultDto
{
    public Guid FacultyId { get; set; }
    public string FacultyName { get; set; }
    public ICollection<User> Users { get; set; }
}

您正在寻找 SelectMany:

var results = context.Faculties.Select(f => new ResultDto
{
    FacultyId = f.Id,
    FacultyName = f.Name,
    Users = f.Groups.SelectMany(g => g.Users).ToList()
}

这将 运行 用于 EF-core 版本,如 5 和 6,也用于 3,但效率稍低。