ASP.NET Core 2.2 Razor页面MVVM查询AspNetUsers和AspNetRoles表

时间:2019-04-06 07:52:15

标签: c# asp.net-core asp.net-identity

.NET Core 2.2,Razor页面,MVVM

我有一个模型,其中包含与AspNetUsers表ID主键的UserId外键关系。如何在查询中包括AspNetUser模型?我想显示与ID关联的UserName。

我不知所措,涉及很多事情。

我认为可能与此有关。

UserManager<IdentityUser> userManager

这是我到目前为止所拥有的。

Models / MyView.cs

namespace MyProject.Models
{
  public class MyView
  {
    [Key]
    public int MyViewId { get; set; }

    [Required]
    [StringLength(450)]
    [ForeignKey("User")] // PK AspNetUsers.Id
    public string UserID { get; set; }

    public virtual ApplicationUser User { get; set; }

    [Required]
    public string Column1 { get; set; }

    [Required]
    public string Column2 { get; set; }

    [Required]
    public string Column3 { get; set; }
  }

  public class ApplicationUser : IdentityUser
  {
  }

Pages / MyViews / Index.cshtml.cs

namespace MyProject.Pages.MyViews
{
  public class ViewAspNetUsersModel : PageModel
  {
    public ApplicationUser AspNetUser { get; set; }

    public IList<MyView> MyView { get; set; }
  }

  public async Task OnGetAsync()
  {
    MyView = await myviews
            .Include(s => s.AspNetUser).ToListAsync();
  }
}

Pages / MyViews / Index.cshtml

@page
@model MyProject.Pages.MyViews.Index

<table class="table">
  <thead>
    <tr>
      <th>@Html.DisplayNameFor(model => model.AspNetUser.UserName)</th>
      <th>@Html.DisplayNameFor(model => model.MyView[0].Column1)</th>
      <th>@Html.DisplayNameFor(model => model.MyView[0].Column2)</th>
      <th>@Html.DisplayNameFor(model => model.MyView[0].Column3)</th>
  </thead>
  <tbody>
    @foreach (var item in Model.MyView)
    {
      <tr>
        <td>@Html.DisplayFor(model => model.AspNetUser.UserName)</td>
        <td>@Html.DisplayFor(modelItem => item.Column1)</td>
        <td>@Html.DisplayFor(modelItem => item.Column2)</td>
        <td>@Html.DisplayFor(modelItem => item.Column3)</td>
      </tr>
    }
  </tbody>
</table>

2 个答案:

答案 0 :(得分:1)

您不需要页面模型中的public ApplicationUser AspNetUser { get; set; },因为您想在foreach循环中显示UserName

假设在ApplicationDbContext中,您已经

public DbSet<MyView> MyViews { get; set; }

您的PageModel:

public class IndexModel: PageModel
{       
    private readonly ApplicationDbContext _context;
    public IndexModel(ApplicationDbContext context)
    {
        _context = context;
    }
    //public ApplicationUser AspNetUser { get; set; }

    public IList<MyView> MyView { get; set; }

    public async Task OnGetAsync()
    {
        MyView = await _context.MyViews
                .Include(s => s.User).ToListAsync();
    }
}

视图中:

@page
@model IndexModel
<table class="table">
<thead>
    <tr>
        <th>@Html.DisplayNameFor(model => model.MyView[0].User.UserName)</th>
        <th>@Html.DisplayNameFor(model => model.MyView[0].Column1)</th>
        <th>@Html.DisplayNameFor(model => model.MyView[0].Column2)</th>
        <th>@Html.DisplayNameFor(model => model.MyView[0].Column3)</th>
    </tr>
</thead>
<tbody>
    @foreach (var item in Model.MyView)
    {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.User.UserName)</td>
            <td>@Html.DisplayFor(modelItem => item.Column1)</td>
            <td>@Html.DisplayFor(modelItem => item.Column2)</td>
            <td>@Html.DisplayFor(modelItem => item.Column3)</td>
        </tr>
    }
</tbody>

如果您想获得所有用户,可以尝试

var users = await _context.Users.ToListAsync();

答案 1 :(得分:0)

有几个文件需要修改才能使它起作用。访问用户数据和角色数据是相关的,因此我将发布答案以包括两者。设置完成后,可以将列添加到AspNetUsers和AspNetRoles,方法是将它们添加到ApplicationUser和ApplicationRole。

使用Visual Studio 2019

我使用.NET Core 2.1创建了该项目,因此主页将具有滑块,然后将其更改为.NET Core 2.2。

Project > IdentityCore Properties > Target Framework

更新依赖项

Tools > NuGet Package Mangager > Manage NuGet Packages for Solution

涉及8个文件

  • 修改或添加前6个文件
  • 添加Pages / MyView文件夹
  • 添加剃须刀页面CRUD
  • 修改页面/MyViews/Index.cshtml

这是8个文件


Startup.cs

using IdentityCore.Models;

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            /*services.AddDefaultIdentity<IdentityUser>()
                .AddEntityFrameworkStores<ApplicationDbContext>();*/
            services.AddIdentity<ApplicationUser, ApplicationRole>(options => options.Stores.MaxLengthForKeys = 128) // preserve string length of keys
               .AddEntityFrameworkStores<ApplicationDbContext>()
               .AddDefaultUI()
               .AddDefaultTokenProviders();

Data / ApplicationDbContext.cs

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using IdentityCore.Models;

namespace IdentityCore.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
        public DbSet<MyView> MyViews { get; set; }
    }
}

页面/共享/_LoginPartial.cshtml

@using Microsoft.AspNetCore.Identity;
@using IdentityCore.Models;

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

Models / ApplicationUser.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace IdentityCore.Models
{
    public class ApplicationUser : IdentityUser
    {
        public ApplicationUser() : base() { }

        public virtual ICollection<MyView> MyViews { get; set; }
    }
}

Models / ApplicationRole.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;

namespace IdentityCore.Models
{
    public class ApplicationRole : IdentityRole
    {
        public ApplicationRole() : base() { }
    }
}

Models / MyView.cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNetCore.Identity;

namespace IdentityCore.Models
{
    public class MyView
    {
        [Key]
        public int MyViewId { get; set; }

        [Required]
        [Column(TypeName = "nvarchar(450)")] // match with primary key
        [ForeignKey("User")]                 // primary key AspNetUseres.Id
        public string UserId { get; set; }

        public virtual ApplicationUser User { get; set; }

        [Required]
        public string Column1 { get; set; }

        [Required]
        public string Column2 { get; set; }

        [Required]
        public string Column3 { get; set; }
    }
}

Pages / MyViews / Index.cshtml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using IdentityCore.Data;
using IdentityCore.Models;

namespace IdentityCore.Pages.MyViews
{
    public class IndexModel : PageModel
    {
        private readonly IdentityCore.Data.ApplicationDbContext _context;

        public IndexModel(IdentityCore.Data.ApplicationDbContext context)
        {
            _context = context;
        }

        public IList<MyView> MyView { get;set; }

        public async Task OnGetAsync()
        {
            MyView = await _context.MyViews
                .Include(m => m.User).ToListAsync();
        }
    }
}

Pages / MyViews / Index.cshtml

@page
@model IdentityCore.Pages.MyViews.IndexModel

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
    <a asp-page="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>@Html.DisplayNameFor(model => model.MyView[0].User)</th>
            <th>@Html.DisplayNameFor(model => model.MyView[0].Column1)</th>
            <th>@Html.DisplayNameFor(model => model.MyView[0].Column2)</th>
            <th>@Html.DisplayNameFor(model => model.MyView[0].Column3)</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model.MyView) {
        <tr>
            <td>@Html.DisplayFor(modelItem => item.User.UserName)</td>
            <td>@Html.DisplayFor(modelItem => item.Column1)</td>
            <td>@Html.DisplayFor(modelItem => item.Column2)</td>
            <td>@Html.DisplayFor(modelItem => item.Column3)</td>
            <td>
                <a asp-page="./Edit" asp-route-id="@item.MyViewId">Edit</a> |
                <a asp-page="./Details" asp-route-id="@item.MyViewId">Details</a> |
                <a asp-page="./Delete" asp-route-id="@item.MyViewId">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>