Using AutoMapper in the Edit action method in an MVC3 application

假装没事ソ 提交于 2019-12-20 19:39:06

问题


Here is my controller code, which works 100% as I need it to. However the POST method isn't using the AutoMapper and that is not OK. How can I use AutoMapper in this action method?

I'm using Entity Framework 4 with the Repository Pattern to access data.

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);
}

If I use AutoMapper, the entity framework reference is lost and the data doesn't persist to the database.

[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);
}

I'm guessing this is caused the Mapper.Map function returning a brand new Product object and because of that, no references to the entity framework graph is being kept. What alternatives do you suggest?


回答1:


I think you just do

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

you may also want to check that you have a non null product first, and also that user is allowed to change that product....



来源:https://stackoverflow.com/questions/8844443/using-automapper-in-the-edit-action-method-in-an-mvc3-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!