这个问题通常是由于 ASP.NET Core 的模型绑定器在执行更新操作时,只会更新模型对象中的已更改属性,而不会清除模型对象中未更改属性的内容所致。这可能会导致数据库存储在更新已更改属性和未更改属性的情况下出现冲突或重复。
解决这个问题的方法是在执行更新操作时使用 DbContext 中的 Update 方法,它会更新整个模型对象而不仅仅是更改的属性。这将确保所有属性都得到正确更新,从而避免出现重复的问题。
以下是一个使用 Update 方法来避免重复的示例:
// GET: /Products/Edit/5
public IActionResult Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var product = _context.Products.SingleOrDefault(m => m.ProductID == id);
if (product == null)
{
return NotFound();
}
return View(product);
}
// POST: /Products/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task Edit(int id, [Bind("ProductID,ProductName,Price")] Product product)
{
if (id != product.ProductID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
// Use the Update method to update the whole model object
_context.Update(product);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(product.ProductID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(product);
}
在这个示例中,我们使用了 DbContext 的 Update 方法来更新整个 product 对象,这将确保模型对象中的所有属性都得到正确更新,从而避免已更改的属性和未更改的属性之间的差异导致的重复问题。