4

MVC 3 Web サイトを構築しています。次のようなモデルがあります。

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

これを実行すると、次のエラーが表示されます。

これは想定内だったと思います。ビュー モデルからモデルへのマッピングでは、完全な 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");
}

しかし、もっと良い方法があるかどうか疑問に思っていましたか?

4

1 に答える 1

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");
}
于 2012-06-26T10:02:47.833 に答える