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

Time:02-01

How could merge nested child entity in parent?

I have these three entities:

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; }
}

Expected results in ResultDto is:

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

CodePudding user response:

You're looking for SelectMany:

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

This will run in EF-core versions like 5 and 6, also in 3, but slightly less efficiently.

  •  Tags:  
  • Related