'The expression 'u.Roles.AsQueryable().Select(r => r.Name)' is invalid inside an 'Include' operation

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


Solution 1:[1]

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
    .Select(user => new { user, rolesNames = user.Roles.Select(role => role.Name) }) 
    .ToListAsync()

Roles will be included under the hood in the Select query. (See @Svyatoslav Danyliv `s comments for more details).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1