我一直在读你应该使用 ViewModels(和 AutoMapper)——所以这是我的初步步骤。
我只是在寻找一些保证,即我正在将我的模型映射到我的视图模型,并且在发回时,我正在从返回的视图模型中正确更新数据库记录:
//
// GET: /Customer/EditPartial
public ActionResult EditPartial(int id)
{
var customerVM = db.Customers.Where(x => x.UserName == User.Identity.Name && x.CustomerId == id).FirstOrDefault();
AutoMapper.Mapper.CreateMap<Customer, CustomerViewModel>();
CustomerViewModel customer = AutoMapper.Mapper.Map<Customer, CustomerViewModel>(customerVM);
return PartialView("CustomerPartial2", customer);
}
//
// POST: /Customer/EditPartial
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditPartial(CustomerViewModel customerviewmodel)
{
if (ModelState.IsValid)
{
Customer customer = db.Customers.Where(x => x.UserName == User.Identity.Name && x.CustomerId == customerviewmodel.CustomerId).FirstOrDefault();
if (customer == null)
{
return HttpNotFound();
}
customer.CustomerName = customerviewmodel.CustomerName;
customer.Email = customerviewmodel.Email;
db.Entry(customer).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return PartialView("CustomerPartial2", customerviewmodel);
}
那么,我的 Get 设置 Automapper 是否正确?
我从 viewmodel 更新 CustomerName 和 Email 的方式是否正确,或者是否有更简单的方法再次使用 AutoMapper?
谢谢,
标记