在我得到这个代码之前:
Department.cs:
public class Department
{
[Key]
public int Id { get; set; }
[Required]
[DisplayName("Department Name")]
public string Name { get; set; }
}
在DepartmentController中添加动作方法:
//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);
}
Add.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; }
}
我不确定是否应该在控制器或视图中添加新属性,以及具体要添加什么。
1条答案
按热度按时间mwg9r5ms1#
如果设备和部门之间存在外键关系,则应添加如下关系:
公共虚拟ICollection设备{ get;} =新列表();
1.设备类应包含导航属性:
公共int部门ID { get;设置; }
公共虚拟部门部门{ get;设置; } =空!;
1.此外,检查您的_appDbContext是否存在关系。