创建用户列表及其角色 DataTable .Net Core 2.1 Razor Pages [英] Create a List of Users and their roles DataTable .Net Core 2.1 Razor Pages

查看:22
本文介绍了创建用户列表及其角色 DataTable .Net Core 2.1 Razor Pages的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,我试图显示所有用户及其分配的角色.

I have a page I'm trying to display all the users and their assigned Roles.

我可以获取我的角色、所有角色和所有用户......但我似乎无法弄清楚如何在同一个查询中获取用户及其角色?

I'm able to get My role, All roles, and All users.... but I cannot seem to figure out how to get the user and their role in the same query?

 public class IndexModel : PageModel
 {
    private readonly FishRoomDbContext _context;

    public IndexModel(FishRoomDbContext application)
    {
        _context = application;
    }

    public List<ApplicationUser> Users { get; private set; }

    public List<IdentityUserRole<string>> UsersRoles { get; set; }  // get my roles or context of user

    public List<IdentityRole> AllRoles { get; private set; }

    public void OnGet()
    {
        Users = _context.Users.ToList();
        UsersRoles = _context.UserRoles.ToList(); // get my roles or context 
        of user
        AllRoles = _context.Roles.ToList();
    }
}

我将如何显示该信息?

推荐答案

public class User{
//Foreign Key Reference
  public virtual ICollection<UserRole> UserRoles { get; set; }
}
public class UserRole{
//Foreign Key Reference
 public int userID{get;set;} //ID field of user
 public virtual User User { get; set; }
}
public partial class FishRoomDbContext : DbContext
{
 public FishRoomDbContext()
    : base("name=ConnectionStringName")
 {
   this.Configuration.LazyLoadingEnabled = false;
 }
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
   modelBuilder.Entity<User>()
            .HasMany(e => e.UserRoles)
            .WithRequired(e => e.User)
            .HasForeignKey(e => e.userID)
            .WillCascadeOnDelete(false);
 }

你的方法

public void OnGet()
    {
        Users = _context.Users.Include("UserRoles").ToList();
        UsersRoles = _context.UserRoles.ToList(); // get my roles or context 
        of user
        AllRoles = _context.Roles.ToList();
    }

我所做的是,我添加了外键引用,也在您的 dbms 中执行此操作.现在,当您调用方法 OnGet() 时,所有用户都将获得他们的角色.角色将在 User.UserRoles 属性中.

What i did is , i added foreign key reference, do it in your dbms too. Now when you will call your method OnGet() all the users will be fetched with their roles. Roles willl be in User.UserRoles property.

这篇关于创建用户列表及其角色 DataTable .Net Core 2.1 Razor Pages的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆