Onl*_*ere 9 c# automapper asp.net-mvc-3
这是我的控制器代码,它可以100%正常工作.但是POST方法没有使用AutoMapper,这不行.如何在此操作方法中使用AutoMapper?
我正在使用Entity Framework 4和Repository Pattern来访问数据.
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);
}
Run Code Online (Sandbox Code Playgroud)
如果我使用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);
}
Run Code Online (Sandbox Code Playgroud)
我猜这是因为Mapper.Map函数返回了一个全新的Product对象,因此没有保留对实体框架图的引用.你有什么选择吗?
Kei*_*las 14
我想你就是这么做的
Product product = _productRepository.FindProduct(model.ProductId);
Mapper.Map(model, product);
_productRepository.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
您可能还想先检查您是否有非空产品,并且该用户也可以更改该产品....