本文介绍了创建用户及其角色的列表DataTable .Net Core 2.1剃刀页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个页面正在尝试显示所有用户及其分配的角色.
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剃刀页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!