I have 3 tables in a NetCore C # project, I cannot form a query to the database to form a complete list of users with roles attached to them
User table
var user = await _context.Users
.Select(x => new
{
x.Id,
x.UserName
}).ToListAsync();
Role table
var role = await _context.Roles
.Select(x => new
{
RoleId = x.Id,
RoleName = x.Name
}).ToListAsync();
and UserRole table (relationship)
var userRole = await _context.UserRoles
.Select(x => new
{
x.RoleId,
x.UserId
}).ToListAsync();
How do you need to build a query for this DTO to be generated?
public class UserRoleDto
{
public int UserId { get; set; }
public string UserName { get; set; }
public IEnumerable<RolesDto> Roles { get; set; }
}
public class RolesDto
{
public int RoleId { get; set; }
public string RoleName { get; set; }
}
and this result was displayed?
[
{
"userId": "1",
"userName": "User1",
"roles": [
{
"roleId": "1",
"roleName": "admin"
},
{
"roleId": "2",
"roleName": "operator"
},
{
"roleId": "3",
"roleName": "support"
}
]
},
{
"userId": "2",
"userName": "User2",
"roles": [
{
"roleId": "2",
"roleName": "operator"
}
]
}
]