如何使用LINQ for Link表?

时间:2018-04-30 16:13:58

标签: c# linq razor

我正在使用.net核心2在剃刀页面上开发webapp。我实现了标准的个人帐户,并且我能够处理数据。

但是,我希望通过显示具有相应角色的用户来扩展我的信息中心。

我有这些表格:

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

当我循环使用@foreach(var user in @Model.users时,我只能(当然)访问AspNetUsers - 表的列。

我想查询所有用户并使用user.Role。

我知道这个解决方案

  var admins = _userManager.GetUsersInRoleAsync("Admin").Result;

但我不想重复自己几次。一切都需要充满活力。我想改变这个角色,因为我以后必须能够对其进行编辑。

所以,我的具体问题是:如何使用LINQ基于我当前的数据库结构和代码来完成以下情况?

我理想的情况

// my .cshtml
<table>
    <tbody>
         @foreach(var user in @Model.users)
         {
             <tr>@user.Name - @user.Role</tr>
         }
    </tbody>
</table>

编辑1 ###

    public class ApplicationUser : IdentityUser
    {
        [NotMapped]
        public virtual ICollection<IdentityRole<string>> Roles { get; set; }
    }

错误:

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.

1 个答案:

答案 0 :(得分:1)

您可以创建一个返回带有角色的用户列表的查询,或者将当前的用户修改为Include这样的角色:

users = _dbContext.Users
    .Include(u => u.Roles)
    .ToList();

现在,您可以使用Razor代码执行此操作:

@foreach(var user in @Model.users)
{
    foreach(var role in user.Roles)
    {
        <tr>@user.Name - @role.Name</tr>
    }
}

注意:您的HTML table代码需要一些工作,因为它没有任何trth/td元素