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

时间:2012-01-13 00:39:03

标签: c# asp.net-mvc-3 automapper

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

我正在使用带有存储库模式的Entity Framework 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对象,因此,没有保留对实体框架图的引用。你有什么选择吗?

1 个答案:

答案 0 :(得分:14)

我想你只是做

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

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