以下是一个示例解决方案,演示了如何在ASP.NET Core 2.2 Razor Pages MVVM中查询AspNetUsers和AspNetRoles表:
1.首先,确保已经安装了ASP.NET Core 2.2 SDK。
2.在Visual Studio中创建一个新的ASP.NET Core Web应用程序项目,选择Razor Pages模板。
3.在Models文件夹中创建一个名为UserViewModel.cs的类,用于存储查询结果:
using System.Collections.Generic;
namespace YourProjectName.Models
{
public class UserViewModel
{
public string UserName { get; set; }
public List Roles { get; set; }
}
}
4.在Pages文件夹中创建一个名为Users.cshtml的Razor页面:
@page
@model UsersModel
@{
ViewData["Title"] = "Users";
}
Users
Username
Roles
@foreach (var user in Model.Users)
{
@user.UserName
@foreach (var role in user.Roles)
{
- @role
}
}
5.在Pages文件夹中创建一个名为Users.cshtml.cs的Razor页面对应的代码文件:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YourProjectName.Models;
namespace YourProjectName.Pages
{
public class UsersModel : PageModel
{
private readonly YourDbContext _context;
public UsersModel(YourDbContext context)
{
_context = context;
}
public List Users { get; set; }
public async Task OnGetAsync()
{
Users = await _context.AspNetUsers
.Include(u => u.UserRoles)
.ThenInclude(ur => ur.Role)
.Select(u => new UserViewModel
{
UserName = u.UserName,
Roles = u.UserRoles.Select(ur => ur.Role.Name).ToList()
})
.ToListAsync();
return Page();
}
}
}
6.确保在YourDbContext中添加对AspNetUsers和AspNetRoles表的DbSet定义:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using YourProjectName.Models;
namespace YourProjectName.Data
{
public class YourDbContext : IdentityDbContext
{
public YourDbContext(DbContextOptions options)
: base(options)
{
}
public DbSet AspNetUsers { get; set; }
public DbSet AspNetRoles { get; set; }
}
}
7.运行应用程序,并导航到"/Users"页面,您将看到AspNetUsers表中的用户名以及与每个用户关联的AspNetRoles表中的角色列表。
请注意,上述示例假定您具有已配置的Identity数据库上下文(YourDbContext)和Identity用户/角色实体(ApplicationUser和ApplicationRole)。您可能需要根据您的项目结构和需求进行一些修改。