【问题标题】:Can't add record to database after adding ICollection property in a Model class在模型类中添加 ICollection 属性后无法将记录添加到数据库
【发布时间】:2022-12-15 17:06:51
【问题描述】:

在我有这段代码之前:

部门.cs:

public class Department
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [DisplayName("Department Name")]
        public string Name { get; set; }
    }

在 DepartmentController 中添加 Action 方法:

        //GET
        public IActionResult Add()
        {
            return View();
        }

        //POST
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Add(Department obj)
        {
            if (_appDbContext.Departments.Where(x => x.Name.Contains(obj.Name)).Any())
            {
                ModelState.AddModelError("Name", "Department name already exists");
            }

            if (ModelState.IsValid)
            {
                _appDbContext.Departments.Add(obj);
                _appDbContext.SaveChanges();
                TempData["success"] = "Department created successfully";

                return RedirectToAction("Index");
            }
            return View(obj);
        }

添加.cshtml:

@model Department

<form method="post">
    <div class="border p-3 mt-4">
        <div class="row pb-2">
            <h2 class="text-primary">Add Department</h2>
            <hr />
        </div>
        @*<div asp-validation-summary="All"></div>*@
        <div class="mb-3">
            <label asp-for="Name" class="mb-1"></label>
            <input asp-for="Name" class="form-control" />
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>
        <button type="submit" class="btn btn-primary" style="width:150px">Add</button>
        <a asp-controller="Department" asp-action="Index" class="btn btn-secondary" style="width:150px">
            Back to List
        </a>
    </div>
</form>

@section Scripts{
    @{
        <partial name="_ValidationScriptsPartial" />
    }
}

上面的代码可以很好地添加记录。 但在对 Department.cs 类进行此更改后它不再起作用(数据库被删除并重新更新以确保重新开始):

public class Department
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [DisplayName("Department Name")]
        public string Name { get; set; }

        public ICollection<Equipment> Equipments{ get; set; }
    }

我不确定是否应该在 Controller 或 View 中添加新属性以及究竟要添加什么。

【问题讨论】:

  • 您的设备型号的代码是什么?如果您在部门中添加新属性,不仅会删除并重新更新数据库以确保重新开始,还会创建新的迁移。

标签: asp.net sql-server entity-framework asp.net-core entity-framework-core


【解决方案1】:

如果 Equipment 和 Department 之间存在外键关系,则应添加如下关系:

  1. ICollection 属性应该添加如下:

    公共虚拟 ICollection 设备 { get; } = 新列表();

  2. 设备类应包含导航属性:

    public int DepartmentId { 得到;放; }

    public virtual Department Department { get;放; } = 空!

  3. 此外,检查您的 _appDbContext 是否存在关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 2018-08-22
    相关资源
    最近更新 更多