在编辑操作方法在MVC3应用程序中使用AutoMapper [英] Using AutoMapper in the Edit action method in an MVC3 application

查看:94
本文介绍了在编辑操作方法在MVC3应用程序中使用AutoMapper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的控制器code,因为我需要它其中工程100%。然而POST方法是不使用AutoMapper那也不行。如何使用AutoMapper在这个动作的方法?

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?

我使用实体框架4 Repository模式来访问数据。

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

如果我使用AutoMapper,实体框架基准丢失,数据不会保留到数据库中。

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

我猜这是造成Mapper.Map函数返回一个全新的产品对象,正因为如此,对实体框架图的引用被保存。你有什么建议的替代品?

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?

推荐答案

我觉得你只是做

 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....

这篇关于在编辑操作方法在MVC3应用程序中使用AutoMapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆