【发布时间】: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