在MVC3应用程序的Edit操作方法中使用AutoMapper

这是我的控制器代码,它可以100%正常工作。 但是POST方法没有使用AutoMapper,那不行。 如何在此操作方法中使用AutoMapper?

我正在使用Entity Framework 4和Repository Pattern来访问数据。

public ActionResult Edit(int id) { Product product = _productRepository.FindProduct(id); var model = Mapper.Map(product); return View(model); } [HttpPost] public ActionResult Edit(ProductModel model) { if (ModelState.IsValid) { Product product = _productRepository.FindProduct(model.ProductId); product.Name = model.Name; product.Description = model.Description; product.UnitPrice = model.UnitPrice; _productRepository.SaveChanges(); return RedirectToAction("Index"); } return View(model); } 

如果我使用AutoMapper,entity framework引用将丢失,并且数据不会持久存储到数据库中。

 [HttpPost] public ActionResult Edit(ProductModel model) { if (ModelState.IsValid) { Product product = _productRepository.FindProduct(model.ProductId); product = Mapper.Map(model); _productRepository.SaveChanges(); return RedirectToAction("Index"); } return View(model); } 

我猜这是因为Mapper.Map函数返回了一个全新的Product对象,因此没有保留对entity framework图的引用。 你有什么选择吗?

我想你就是这么做的

  Product product = _productRepository.FindProduct(model.ProductId); Mapper.Map(model, product); _productRepository.SaveChanges(); 

您可能还想先检查您是否有非空产品,并且该用户也可以更改该产品….