4

MVC 3 웹 사이트를 구축 중입니다. 사용자가 내가 변화를 지속하고자하는 편집이 완료되면Entity Framework : ViewModel에서 도메인 모델

public class SurveyEditViewModel 
{ 
    public Guid Id { get; set; } 

    public string Name { get; set; } 

    public string Description { get; set; } 

    public DateTime DateStart { get; set; } 

    public DateTime DateEnd { get; set; } 
} 

:

public class Survey 
{ 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public Guid Id { get; set; } 

    public string Name { get; set; } 

    public string Description { get; set; } 

    public DateTime DateStart { get; set; } 

    public DateTime DateEnd { get; set; } 

    // Not in view 
    public DateTime DateCreated { get; set; } 

    // Not in view 
    public DateTime DateModified { get; set; } 
} 

나는 또한 설문 조사 정보를 편집 할 수있는 뷰 모델을 가지고이를 바탕으로 : 나는 모델과 같이 찾고 있습니다. 내 저장소에서

[HttpPost] 
    public ActionResult Edit(SurveyEditViewModel model) 
    { 
     // Map the view model to a domain model using AutoMapper 
     Survey survey = Mapper.Map<SurveyEditViewModel, Survey>(model); 

     // Update the changes 
     _repository.Update(survey); 

     // Return to the overview page 
     return RedirectToAction("Index"); 
    } 

(지금에 대한 일반적인 하나) 나는 다음과 같은 코드가 있습니다 :이 나는 다음과 같은 오류가 실행

public void Update(E entity) 
    { 
     using (ABCDataContext context = new ABCDataContext()) 
     { 
      context.Entry(entity).State = System.Data.EntityState.Modified; 
      context.SaveChanges(); 
     } 
    } 

을 : "스토어 업데이트 여기 내 컨트롤러 포스트 액션이다 , insert 또는 delete 문이 예기치 않은 행 수 (0)에 영향을 미쳤습니다. 엔티티가로드 된 후 엔티티가 수정되거나 삭제되었을 수 있습니다 .OptionsStateManager 항목을 새로 고칩니다. "

나는 이것이 예상되었다고 생각합니다. 뷰 모델에서 모델로 매핑해도 완전한 측량 객체가 될 수 없습니다.

컨트롤러를 다음과 같이 수정할 수 있습니다. 그리고 나서 작동합니다 :

그러나 더 좋은 방법이 있는지 궁금합니다.

답변

12
[HttpPost] 
public ActionResult Edit(SurveyEditViewModel model) 
{ 
    // Fetch the domain model to update 
    var survey = _repository.Find(model.Id); 

    // Map only the properties that are present in the view model 
    // and keep the other domain properties intact 
    Mapper.Map<SurveyEditViewModel, Survey>(model, survey); 

    // Update the changes 
    _repository.Update(survey); 

    // Return to the overview page 
    return RedirectToAction("Index"); 
} 
+0

위대한! 나는 이것을 답으로 표시 할 것이다. – Aetherix

+0

@DarinDimitrov이 예제를 따르는 경우 엔티티에서 변경 내용 추적을 설정해야합니까? 내가 설정하면 문제가 많이 생길 것 같아. – MuriloKunze

관련 문제