【发布时间】:2013-05-07 13:28:23
【问题描述】:
我一直在读到您应该使用 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?
谢谢,
标记
【问题讨论】:
-
设置看起来不错,除了变量的命名(customerVM 对应于 Customer 实体,customer 对应于视图模型)。您还可以在 post 方法中使用 automapper 将 vm 映射回客户实体。
-
您遇到问题了吗?如果没有,这应该张贴在codereview.stackexchange.com 上。
-
谢谢 - 没问题 - 只是我不确定如何在 POST 中使用 AutoMapper - 我这样做的方式似乎根本没有使用 AutoMapper。
标签: asp.net-mvc asp.net-mvc-3 entity-framework automapper