我正在嘗試使用視圖模型更新記錄。我的模型中有 CreatedBy 和 DateCreated 列,我不希望它們被更改,所以我沒有將它們包含在我的視圖模型中,但是當我更新記錄時,它們也會更新。如果它們不可為空,它們會拋出錯誤。我究竟做錯了什么?
位置.cs
public int LocationId { get; set; }
public string LocationName { get; set; }
public string Address { get; set; }
[ForeignKey("LocationCreator")]
public string? CreatedBy { get; set; }
public AppUser? LocationCreator { get; set; }
[ForeignKey("LocationModifier")]
public string? ModifiedBy { get; set; }
public AppUser? LocationModifier { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
位置編輯VM
public int LocationId { get; set; }
public string LocationName { get; set; }
public string Address { get; set; }
public string? Description { get; set; }
public string? ModifiedBy { get; set; }
public DateTime DateModified { get; set; }
控制器
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, LocationEditVM locationEditVM)
{
if (id != locationEditVM.LocationId)
{
return NotFound();
}
var currentUser = await userManager.GetUserAsync(User);
locationEditVM.ModifiedBy = currentUser.Id;
locationEditVM.DateModified = DateTime.Now;
if (ModelState.IsValid)
{
try
{
var location = mapper.Map<Location>(locationEditVM);
_context.Update(location);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!LocationExists(locationEditVM.LocationId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(locationEditVM);
}
uj5u.com熱心網友回復:
如果要保留現有值,則應從資料庫中獲取現有物體,然后將視圖模型中的值映射到該物體。
目前在您的 EF 模型中,它會獲取視圖模型中沒有的欄位的默認值,并最終將它們設定為 DB。
uj5u.com熱心網友回復:
您在映射時犯了錯誤。根據您的模型和物體模型,物體模型獲得相應列的默認值,例如CreatedBy并且DateCreated不是您的視圖模型的一部分。
在更新時,您使用映射器將視圖模型映射到物體,因此您的物體列設定了各個資料型別的默認值,因為相同的資料型別將更新到資料庫。
如果你想避免這種情況,那么你需要像其他列一樣在視圖模型中攜帶這兩個列,或者你必須在更新時手動更新它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/416836.html
標籤:
