实体框架:ViewModel到域模型

时间:2012-06-26 10:00:11

标签: asp.net-mvc-3 entity-framework entity-framework-4 automapper

我正在建立一个MVC 3网站。我的模型看起来像这样:

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

基于此,我还有一个用于编辑调查信息的视图模型:

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

当用户完成编辑时,我希望保留更改。这是我的控制器后期行动:

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

执行此操作时,我收到以下错误:“存储更新,插入或删除语句影响了意外的行数(0)。实体可能已被修改或删除,因为实体已加载。刷新ObjectStateManager条目。 “

我想这是可以预料的。从视图模型到模型的映射不会给我一个完整的Survey对象。

我可以将我的控制器修改为这样。然后它起作用:

[HttpPost]
public ActionResult Edit(SurveyEditViewModel model)
{

    // Map the model to a real survey
    survey = _repository.Find(model.Id);
    survey.Name = model.Name;
    survey.Description = model.Description;
    survey.DateStart = model.DateStart;
    survey.DateEnd = model.DateEnd;

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

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

但我想知道是否有更好的方法?

1 个答案:

答案 0 :(得分: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");
}