gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:42:22 25 4
gpt4 key购买 nike

这是我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com