I am working on a webapp in razor pages using .net core 2. I implemented the standard individual accounts and I am able to work with the data.
However, I'd like to extend my dashboard by displaying the users with its corresponding role.
I have these tables:
mssql
AspNetUsers
UserId | Email | Password | Etc
AspNetRoles
RoleId | RoleName
AspNetUserRoles
UserId | RoleId
users.cshtml.cs
private readonly ApplicationDbContext _dbContext;
public List<ApplicationUser> users { get; set; }
public UsersModel(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async void OnGet()
{
users = _dbContext.Users.ToList();
}
When I loop use @foreach(var user in @Model.users
, I can only (ofcourse) access the columns of the AspNetUsers
-table.
I'd like to query over all my users and use user.Role for example.
I am aware of this solution
var admins = _userManager.GetUsersInRoleAsync("Admin").Result;
But I don't want to repeat myself a couple of times. Everything needs to be dynamic. And I'd like to change this role, since I have to be able to edit it later on.
So, my concrete question is: how can I accomplish the following situation based on my current database structure and code by using LINQ?
My ideal situation
// my .cshtml
<table>
<tbody>
@foreach(var user in @Model.users)
{
<tr>@user.Name - @user.Role</tr>
}
</tbody>
</table>
edit 1 ###
public class ApplicationUser : IdentityUser
{
[NotMapped]
public virtual ICollection<IdentityRole<string>> Roles { get; set; }
}
Error:
Unhandled Exception: System.InvalidOperationException: The property 'Roles' is not a navigation property of entity type 'ApplicationUser'. The 'Include(string)' method can only be used with a '.' separated list of navigation property names.