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

10

这是我的控制器代码,它以我需要的方式完美地工作。但是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,那么Entity Framework的引用会丢失,数据就不能持久化到数据库中。
[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 对象,因此没有保留对实体框架图的引用。你有什么其他建议吗?


你遇到的问题不太清楚。你说你的POST方法没有使用Automapper,但我在你的[HttpPost]方法中没有看到任何Automapper代码。 - Robert Harvey
你可能没有正确地返回内容? - Keith Nicholas
不确定他的意思是AutoMapper,我认为他的意思是“modelbinder”,但我不能百分之百确定。 - Keith Nicholas
我编辑了更多细节,应该能让问题更清晰。我的意思不是ModelBinder,而是实际的库叫做AutoMapper。 - Only Bolivian Here
哦,你想让这个映射到一个已存在的对象上...你现在做的是将一个ProductModel转换成一个新的Product对象。 - Keith Nicholas
@KeithNicholas:是的,我知道这是个问题。你能提供替代方案吗?我不想创建一个新的Product对象,但Mapper.Map()方法会这样做。除非我漏掉了什么。 - Only Bolivian Here
1个回答

15
我认为你只需要这样做。
 Product product = _productRepository.FindProduct(model.ProductId);
 Mapper.Map(model, product);
 _productRepository.SaveChanges();

您可能还需要检查您是否拥有非空产品,并且用户有权更改该产品....


正确的做法是,实际上我们需要为编辑方法的Get和Post创建Map。对于Get,它是从领域模型到视图模型的映射;对于Post,它是从视图模型到领域模型的映射。请参考这里,希望能帮助到某些人。 - Shaiju T

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接