我有一个页面正在尝试显示所有用户及其分配的角色。
我能够获得我的角色,所有角色和所有用户...。但是我似乎无法弄清楚如何在同一查询中获得用户及其角色?
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();
}
}
我将如何显示该信息?
答案 0 :(得分:2)
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
属性中。