Search code examples
c#linqasp.net-coreentity-framework-core

How to convert query for many-to-many to DTO using EF Core LINQ?


I have two tables (autogenerated by EF Core scaffold):

public partial class Role : IEntityWithDTO<ClientRoleDTO>
{
    public Guid Id { get; set; }

    public string Name { get; set; } = null!;

    public virtual ICollection<User> Users { get; set; } = new List<User>();
}

public partial class User : IEntityWithDTO<UserDTO>
{
    public Guid Id { get; set; }

    public string Login { get; set; } = null!;
    public string Pass { get; set; } = null!;

    public virtual ICollection<Role > Roles { get; set; } = new List<Role>();
}

And also this class UserDTO:

public class UserDTO: IDTO
{
    public required Guid Id { get; set; }
    public required string Login { get; set; }
    public List<string>? Roles { get; set; }
}

How to make a query to return UserDTO with list of Role names?

I successfully get only User with list of Role as objects, when I wrote this code:

[HttpGet]
[Route("/user")]
public async Task<IActionResult> GetUserAsync([FromQuery] Guid userId)
{
    using var dbContext = new DatabaseContext();
    var user = await dbContext.Users
                              .Where(user => user.Id == userId)
                              .Include(user => user.Roles)
                              .FirstOrDefaultAsync();
        
    if (group is not null)
        return Ok(user);
    else
        return NotFound();
}

Solution

  • Can you try this code, it selects the required properties from the User entity and populates the Roles property of the UserDTO with the role names obtained from the corresponding Role entities

    [HttpGet]
    [Route("/user")]
    public async Task<IActionResult> GetUserAsync([FromQuery] Guid userId)
    {
        using var dbContext = new DatabaseContext();
        var userDto = await dbContext.Users
            .Where(user => user.Id == userId)
            .Select(user => new UserDTO
            {
                Id = user.Id,
                Login = user.Login,
                Roles = user.Roles.Select(role => role.Name).ToList()
            })
            .FirstOrDefaultAsync();
    *emphasized text*
        return userDto != null ? Ok(userDto) : NotFound();
    }