I’m a bit confused as to the correct way to save changes to my edit model object in ASP.NET MVC 3 using EF4, especially when I want to do some server-side clean-up just before saving. My action method is:
[HttpPost]
public ActionResult Edit(int id, EmployeeEditModel employeeEditModel) {
var originalEmployee = db.Employees.Single(c => c.Id == id);
// if I don't do this here, I can't check for complex model errors that follows
employeeEditModel.Employee.LastHireDate = employeeEditModel.Employee.LastHireDate.Date;
employeeEditModel.Employee.EmployeeNumber = employeeEditModel.Employee.EmployeeNumber.ToUpper();
if (employeeEditModel.Employee.LastHireDate < employeeEditModel.Employee.OriginalHireDate) {
ModelState.AddModelError("Employee.LastHireDate", "Last Hire Date cannot occur before Original Hire Date.");
}
if (ModelState.IsValid) {
UpdateModel(originalEmployee, "Employee");
// if I don't do this here, these changes won't be saved
originalEmployee.LastHireDate = originalEmployee.LastHireDate.Date;
originalEmployee.EmployeeNumber = originalEmployee.EmployeeNumber.ToUpper();
db.SaveChanges();
return RedirectToAction("Index");
}
return View(getEmployeeEditModel(id));
}
You can see I want to clean up a couple items such as dropping off the time portion in a DateTime field, converting another to uppercase, and trimming whitespace off another (not shown). This is a representative sample of some fields that I can sanitize for which I ought not need to bother the user.
The problem is I seem to have to do this twice in the code I’ve found myself in (refer to the comments in the code). I’m updating an edit model that contains a handful of objects that are stored logically in separate tables.
This code works, but isn’t how I know it should be. Should I be using UpdateModel() or something else in this situation? How can I avoid repeating myself in cleaning up both objects?
I see two options here:
Start with
UpdateModeland do your cleanup only on the EF object. If you have model errors, just don’t commit before leaving the action.Instead of using
UpdateModeluse AutoMapper for updating your EF model object with teh cleaned values of your ViewModel object.