Reputation: 583
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();
}
}
How would I go about displaying that info?
Upvotes: 1
Views: 598
Reputation: 831
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);
}
Your Method
public void OnGet()
{
Users = _context.Users.Include("UserRoles").ToList();
UsersRoles = _context.UserRoles.ToList(); // get my roles or context
of user
AllRoles = _context.Roles.ToList();
}
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.
Upvotes: 2