简体   繁体   English

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

[英]ASP.NET Core 2.2 Razor Pages MVVM Query the AspNetUsers and AspNetRoles Tables

.NET Core 2.2, Razor Pages, MVVM .NET Core 2.2,Razor页面,MVVM

I have a model that includes a UserId foreign key relation to the AspNetUsers table Id primary key. 我有一个模型,其中包括与AspNetUsers表ID主键的UserId外键关系。 How do I include the AspNetUser model in the query? 如何在查询中包括AspNetUser模型? I want to display the UserName associated with the Id. 我想显示与ID关联的UserName。

I'm at a loss as to what to do, there is a lot involved. 我对做什么不知所措,涉及很多事情。

I think it may have something to do with this. 我认为这可能与此有关。

UserManager<IdentityUser> userManager

Here is what I have so far. 这是我到目前为止所拥有的。

Models/MyView.cs 型号/ 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 页/ 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 页/ 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>

You do not need a public ApplicationUser AspNetUser { get; set; } 您不需要public ApplicationUser AspNetUser { get; set; } public ApplicationUser AspNetUser { get; set; } public ApplicationUser AspNetUser { get; set; } in page model since you want to show the UserName in the foreach loop. public ApplicationUser AspNetUser { get; set; } ,因为您希望在foreach循环中显示UserName

Assume in ApplicationDbContext, you have 假设在ApplicationDbContext中,您有

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

Your PageModel: 您的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();
    }
}

In view: 鉴于:

@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>

If you would like to get all Users, you could try 如果您想获得所有用户,可以尝试

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

There are several files that need to be modified to get this to work. 有几个文件需要修改才能使它起作用。 Accessing the User data and the Role data are related so I am posting the answer to include both. 访问用户数据和角色数据是相关的,因此我将发布答案以包括两者。 Once you have this set up, you can add columns to AspNetUsers and AspNetRoles by adding them to ApplicationUser and ApplicationRole. 设置完成后,可以将列添加到AspNetUsers和AspNetRoles,方法是将它们添加到ApplicationUser和ApplicationRole。

Using Visual Studio 2019 使用Visual Studio 2019

I created the project with .NET Core 2.1 so the homepage would have the slider, then I changed it to .NET Core 2.2. 我使用.NET Core 2.1创建了项目,因此主页将具有滑块,然后将其更改为.NET Core 2.2。

Project > IdentityCore Properties > Target Framework

Update the dependencies 更新依赖项

Tools > NuGet Package Mangager > Manage NuGet Packages for Solution

There are 8 files involved 涉及8个文件

  • Modify or add the first 6 files 修改或添加前6个文件
  • Add the Pages/MyView folder 添加页面/ MyView文件夹
  • Add Razor Page CRUD 添加剃刀页面CRUD
  • Modify Pages/MyViews/Index.cshtml 修改页面/MyViews/Index.cshtml

Here are the 8 files 这是8个文件


Startup.cs 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 数据/ 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; }
    }
}

Pages/Shared/_LoginPartial.cshtml 页/共享/ _LoginPartial.cshtml

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

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

Models/ApplicationUser.cs 型号/ 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 型号/ 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 型号/ 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 页/ 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 页/ 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 Razor Pages 在 Asp.NET Core 2.2 中找不到 ViewComponent - ViewComponent not found in Asp.NET Core 2.2 using Razor Pages 在razor,asp.net Core 2.2页面之间传递值 - Passage of values ​between pages razor, asp.net Core 2.2 ASP.NET Core 2.2 Razor Pages 为什么 OnPost() 有效,而 OnPostAsync() 无效? - ASP.NET Core 2.2 Razor Pages why does OnPost() work, but OnPostAsync() doesn't? 如何在asp.net核心剃须刀页面2.2中设置日期格式和区域性 - How to set date formats and culture in asp.net core razor pages 2.2 带ASP.NET Core 2.2的Razor页面中的嵌套/子区域 - Nested/Sub-Areas in Razor Pages w/ASP.NET Core 2.2 IIS 部署不能在 asp.net core 2.2 razor 页面中包含 wwwroot 文件夹的文件 - IIS deployment cannot contains files for wwwroot folder in asp.net core 2.2 razor pages 如何将ASP.NET Core 2.2 Razor页面与MySql数据库连接? - How to connect ASP.NET Core 2.2 Razor pages with MySql database? 如何从 ASP.NET Razor 页面中的.cshtml 页面访问 AspNetUsers 中的数据? - How to access data in AspNetUsers from .cshtml pages in ASP.NET Razor pages? 如何在 asp.net 内核 razor 页面 MVVM 之间传递或引用 model - how to pass or reference model between asp.net core razor pages MVVM ASP.NET Core Razor页面的路由 - Routing for ASP.NET Core Razor Pages
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM