Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading