I'm having an issue while trying to get users with their roles. What I want to do is to get users with their corresponding role but with only the value of the roles such as roles: ["ADMIN", "USER"]
.
Here's my code:
public async Task<ActionResult<IEnumerable<User>>> GetAll()
{
return await _context.User.Include(u => u.Roles.Select(r => r.Name)).ToListAsync();
}
CodePudding user response:
Include
is used to load related entities from context via foreign keys or navigation properties.
I think you should rewrite your query in the following way:
_context
.User
.Include(user => user.Roles) // Add roles to a query
.Select(user => new { user, rolesNames = user.Roles.Select(role => role.Name) }) // Select user with role names. Note that it is in anonymous class and you would probably need to create a separate dto for it
.ToListAsync() // Fetch data from database