映射 属性 "role"(用户 table 中的外键)与角色 Table dotNet Core

Mapping property "role"(foreign key in User table) with the Role Table dotNet Core

我尝试通过为用户设置角色来创建用户。
角色 属性 是 class 用户中的必填字段。
问题是当我做了一个标记来从角色 table 检索数据以便能够将角色设置为用户时,插入查询不起作用。用户 table 具有属性 "roleId" 但用户 Class 具有来自角色 Class.

的 "role" 属性

我会把 UserCreate Razor 页面的代码和我使用的模型放在一起。

UserCreate.cshtml:

@page
@model SprintOneBack.UserCreateModel

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

<h1>Create</h1>

<h4>User</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="User.Nom" class="control-label"></label>
                <input asp-for="User.Nom" class="form-control" />
                <span asp-validation-for="User.Nom" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="User.Email" class="control-label"></label>
                <input asp-for="User.Email" class="form-control" />
                <span asp-validation-for="User.Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="User.password" class="control-label"></label>
                <input asp-for="User.password" class="form-control" />
                <span asp-validation-for="User.password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="User.role" class="control-label"></label>
                <select asp-for="User.role" class="form-control" asp-items="@(new SelectList(Model.displayRoles, "Id", "Label"))">
                    <option value="" selected disabled>-- select Role --</option>
                </select>
                @*<input asp-for="User.role.Label" class="form-control" />*@
                <span asp-validation-for="User.role" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-page="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

UserCreateModel.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.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using SprintOneBack.Model;

namespace SprintOneBack
{
    public class UserCreateModel : PageModel
    {
        private readonly ApplicationDbContext _context;

        public UserCreateModel(ApplicationDbContext context)
        {
            _context = context;
            displayRoles = _context.Role.ToList();
        }

        public IActionResult OnGet()
        {
            return Page();
        }

        public IEnumerable<Role> displayRoles { get; set; }

        public async Task OnGetRoles()
        {
            displayRoles = await _context.Role.ToListAsync();
        }

        [BindProperty]
        public User User { get; set; }

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.User.Add(User);
            await _context.SaveChangesAsync();

            return RedirectToPage("./UserIndex");
        }
    }
}

用户Class:

public class User
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Nom { get; set; }
    [Required]
    public string Email { get; set; }
    [Required]
    public string password { get; set; }
    [Required]
    public Role role { get; set; }
}

角色Class:

public class Role
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Label { get; set; }
}

用户 Table 以及角色 Table:

"roleId"字段是ef core自动生成的外键。它指的是角色 table 中的关键字段。

您可以将代码更改为以下内容:

UserCreate.cshtml:

  <label asp-for="User.role" class="control-label"></label>
  <select asp-for="User.role.Id" class="form-control" asp-items="@(new SelectList(Model.displayRoles, "Id", "Label"))">
      <option value="" selected disabled>-- select Role --</option>
  </select>  

UserCreateModel.cshtml.cs:

public async Task<IActionResult> OnPostAsync()
    {
        ModelState.Remove("User.Role.Label");
        if (!ModelState.IsValid)
        {
            return Page();
        }
        Role role = _context.Role.Find(User.role.Id);
        User.role = role;
        _context.User.Add(User);
        await _context.SaveChangesAsync();

        return RedirectToPage("./UserIndex");
    }

我添加了一个属性 roleId 作为一个整数,我指定它是 User table 中的列 roleId ,并保留了角色属性(所以 ef 知道有一个外键来自 Role Table) 并重新生成 Tables。当我重新生成剃刀页面时,我有一个漂亮的 select html 标签来列出数据库中每个用户的所有角色。

代码现在看起来像这样:

public class User
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Nom { get; set; }
    [Required]
    public string Email { get; set; }
    [Required]
    public string password { get; set; }
    [Column("roleId")]
    public int roleId { get; set; }
    public Role role { get; set; }
}

CreateUser.cshtml :

<h4>User</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="User.Nom" class="control-label"></label>
                <input asp-for="User.Nom" class="form-control" />
                <span asp-validation-for="User.Nom" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="User.Email" class="control-label"></label>
                <input asp-for="User.Email" class="form-control" />
                <span asp-validation-for="User.Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="User.password" class="control-label"></label>
                <input asp-for="User.password" class="form-control" type="password" />
                <span asp-validation-for="User.password" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="User.roleId" class="control-label"></label>
                <select asp-for="User.roleId" class ="form-control" asp-items="ViewBag.roleId"></select>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>