2012-01-13 2 views
9

여기에 필요에 따라 100 % 작동하는 내 컨트롤러 코드가 있습니다. 그러나 POST 메서드는 AutoMapper를 사용하고 있지 않으며 정상적으로 작동하지 않습니다. 이 작업 방법에서 AutoMapper를 어떻게 사용할 수 있습니까?MVC3 응용 프로그램의 편집 작업 메서드에서 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 기능을 발생하고 그 때문에, 엔티티 프레임 워크 그래프에 대한 참조가 유지되고 있지 같은데요. 어떤 대안을 제안합니까?

+0

을 생각한다 겪고있는 문제가 무엇인지 확인하십시오. POST 메소드가 Automapper를 사용하지 않는다고하지만, 당신의'[HttpPost]'메소드에 Automapper 코드가 보이지 않습니다. –

+0

당신은 아마도 옳은 것을 다시 게시하지 않을 것입니까? –

+0

그가 automapper를 의미하는지 확실하지 않다 Robert는 "modelbinder"를 의미한다고 생각하지만 나는 100 % 확실하지 않다. –

답변

13

나는 그것은 아니다 그냥

당신은 또한 당신이 먼저 null 이외의 제품을 가지고 있고, 또한 사용자가 해당 제품을 변경할 수 있는지 확인 할 수 있습니다
Product product = _productRepository.FindProduct(model.ProductId); 
Mapper.Map(model, product); 
_productRepository.SaveChanges(); 

....

+0

Dang, slick! 이것은 매력처럼 작동합니다. 고맙습니다! –

+0

정확한지, 실제로 ** 편집 방법 가져 오기 및 게시를위한 맵 생성 **, ViewModel 매핑을위한 도메인 모델 가져 오기 및 도메인 모델 매핑에 ViewModel 게시 : [http : //] /stackoverflow.com/a/26908339/2218697) 희망은 누군가를 돕습니다. – stom

관련 문제