ASP.NET 6中DbSet更新方法失效,执行时新增数据而非更新
ASP.NET 6 Edit操作新增数据而非更新的解决方法
问题原因
- 主键未传递:Edit视图的表单没有提交
CategoryID(主键字段),导致Post方法接收的Category对象中CategoryID为null。EF Core会将主键为null的实体判定为新实体,执行插入操作而非更新。 - 主键可空设置:模型中主键
CategoryID被定义为可空类型int?,进一步干扰了EF Core对现有实体的识别逻辑。
解决方案
方案1:在视图中添加主键隐藏字段
在Edit.cshtml的表单内部,新增一个隐藏字段传递主键值,确保Post请求能携带CategoryID:
@model Category <form method="post" asp-action="Edit"> <!-- 添加隐藏字段传递主键 --> <input type="hidden" asp-for="CategoryID" /> <div class="border p-3 mt-4"> <div class="row pb-2"> <h2 class="text-primary">Edit Category</h2> <hr/> <div asp-validation-summary="All"></div> </div> <div class="mb-3" style="width: 500px;clear: both;"> <label asp-for="Name"></label> <input style="width: 100%;clear: both;" asp-for="Name" class="form-control" /> <span asp-validation-for="Name" class="text-bg-danger"></span> </div> <div class="mb-3" style="width: 500px;clear: both;"> <label asp-for="DisplayOrder"></label> <input style="width: 100%;clear: both;" asp-for="DisplayOrder" class="form-control" /> <span asp-validation-for="DisplayOrder" class="text-bg-danger"></span> </div> <button type="submit" class="btn btn-primary" style="width:150px;">Update</button> <a asp-controller="Category" asp-action="Index" class="btn btn-secondary" style="width:150px">Back to List</a> </div> </form>
方案2:修改Post方法,采用先查询再更新的安全模式
这种方式可以避免过度提交风险(比如用户篡改视图未暴露的字段),同时确保EF Core准确识别现有实体:
//POST [HttpPost] [ValidateAntiForgeryToken] public IActionResult Edit(int id, Category obj) { // 校验传入ID与实体ID一致性 if (id != obj.CategoryID) { return NotFound(); } if (obj.Name == obj.DisplayOrder.ToString()) { ModelState.AddModelError("name", "The DisplayOrder cannot exactly match the Name."); } if (ModelState.IsValid) { try { var categoryFromDb = _db.Categories.Find(id); if (categoryFromDb == null) { return NotFound(); } // 手动更新需要修改的属性 categoryFromDb.Name = obj.Name; categoryFromDb.DisplayOrder = obj.DisplayOrder; _db.SaveChanges(); return RedirectToAction("Index", "Category"); } catch (DbUpdateConcurrencyException) { if (!CategoryExists(obj.CategoryID.GetValueOrDefault())) { return NotFound(); } else { throw; } } } return View(obj); } // 辅助方法:检查分类是否存在 private bool CategoryExists(int id) { return _db.Categories.Any(e => e.CategoryID == id); }
额外优化:修正模型主键类型
主键通常不应该设置为可空类型,将CategoryID改为非空int:
public class Category { [Key] public int CategoryID { get; set; } // 移除问号,改为非空int [Required] public string Name { get; set; } [DisplayName("Display Order")] [Range(1,100,ErrorMessage ="Not in Range of Display Order")] public int DisplayOrder { get; set; } public DateTime CreatedDateTime { get; set; } = DateTime.Now; }
内容的提问来源于stack exchange,提问作者MohammadSH
相关产品推荐
相关产品推荐

