I am trying to update a record using a view model. I have CreatedBy and DateCreated columns in my model and I don't want them ever changed so I didn't include them in my viewmodel, yet when I update the record, they get updated too. And if they're not nullable, they throw error. What am I doing wrong?
Location.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; }
LocationEditVM
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; }
Controller
[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);
}
CodePudding user response:
If you want to keep existing values, you should get the existing entity from the DB and then map values from the view model to that.
Currently in your EF model it gets the default values for the fields that you didn't have in the view model and end up setting those to DB.
CodePudding user response:
You are made mistake at the time of mapping. As per your model and entity model the entity model get default value of respective column such as CreatedBy and DateCreated is not part of your view model.
At the time of updating you are map viewmodel to entity using mapper, So your entity columns set the default value of respective data types as same will updated to database.
If you want to avoid that then you need to carry both column in viewmodel like other columns or you have to update that manually at the time of updating.
