这是我的控制器代码,它 100% 按照我的需要工作。但是 POST 方法没有使用 AutoMapper,这是不行的。如何在此操作方法中使用 AutoMapper?
我使用实体框架 4 和存储库模式来访问数据。
public ActionResult Edit(int id)
{
Product product = _productRepository.FindProduct(id);
var model = Mapper.Map<Product, ProductModel>(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,实体框架引用就会丢失,并且数据不会保留到数据库中。
[HttpPost]
public ActionResult Edit(ProductModel model)
{
if (ModelState.IsValid)
{
Product product = _productRepository.FindProduct(model.ProductId);
product = Mapper.Map<ProductModel, Product>(model);
_productRepository.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
我猜测这是导致 Mapper.Map 函数返回一个全新的 Product 对象,因此,没有保留对实体框架图的引用。您建议什么替代方案?
我认为你只是这样做
Product product = _productRepository.FindProduct(model.ProductId);
Mapper.Map(model, product);
_productRepository.SaveChanges();
您可能还想首先检查您是否有一个非空产品,并且还允许该用户更改该产品......
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)