c# - 在 MVC3 应用程序的编辑操作方法中使用 AutoMapper

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

这是我的 Controller 代码,它在我需要时 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, 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 对象,因此没有保留对 Entity Framework 图的引用。您有什么建议?

最佳答案

我觉得你就是这样

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

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

关于c# - 在 MVC3 应用程序的编辑操作方法中使用 AutoMapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8844443/

相关文章:

c# - 使用 TimeZoneInfo.ConvertTime 时夏令时日期错误?

javascript - 将带有列表的 JS 对象转换为 C# 列表

c# - WPF MenuItem 绑定(bind)问题

c# - 带模型的 mvc 上传文件 - 第二个参数发布的文件为空

c# - 使用 AutoMapper 从 POCO 映射到 NHibernate 代理对象时出错

c# - Automapper 条件语言映射

java - HTML 发布请求(登录表单)

c# - 某些页面上的 Cookie 为空,但其他页面上没有

c# - 如何访问字段的 System.ComponentModel.DataAnnotations 显示名称属性

c# - AutoMapper - 使用自定义类型转换器将数据表映射到类对象