使用或不使用AutoMapper“合并”模型和ViewModel?

时间:2012-04-20 14:46:30

标签: asp.net-mvc-2 viewmodel automapper

我目前正在使用ViewModels将我的视图与实际的模型结构分开。

例如,我有一个用户持久性实体和一个包含所有信息的MyProfile ViewModel,用户可以自己更改。 对于从User到MyProfile的转换,我使用的是Automapper。

现在用户回复了他的(已更改)信息后,我需要保存这些信息。但是ViewModel中的信息并不完整,当AutoMapper从ViewModel创建用户持久性实体时,重要信息会丢失。

我不想将此信息公开给视图层,尤其是隐藏的表单元素。

所以我需要一种方法将ViewModel合并到持久性实体中。我可以使用AutoMapper执行此操作,还是必须手动执行此操作?

示例:

我的用户类包含ID,名字,姓氏,用户名和密码。用户应该只在他的个人资料中编辑他的名字和姓氏。因此,我的ProfileViewModel包含ID,名字和姓氏。从表单中回发信息后​​,Automapper从传输的ProfileViewModel创建一个User对象,在此对象中只设置ID,Firstname和Lastname。将此实体提供给我的存储库时,我丢失了用户名和密码信息。

1 个答案:

答案 0 :(得分:12)

  

所以我需要一种方法将ViewModel合并到持久性实体中。我可以吗   使用AutoMapper执行此操作,还是必须手动执行此操作?

是的,您可以使用AutoMapper执行此操作。例如:

public class Model
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ViewModel
{
    public string Name { get; set; }
}

class Program
{
    static void Main()
    {
        // define a map (ideally once per appdomain => usually goes in Application_Start)
        Mapper.CreateMap<ViewModel, Model>();

        // fetch an entity from a db or something
        var model = new Model
        {
            Id = 5,
            Name = "foo"
        };

        // we get that from the view. It contains only a subset of the
        // entity properties
        var viewModel = new ViewModel
        {
            Name = "bar"
        };

        // Now we merge the view model properties into the model
        Mapper.Map(viewModel, model);

        // at this stage the model.Id stays unchanged because
        // there's no Id property in the view model
        Console.WriteLine(model.Id);

        // and the name has been overwritten
        Console.WriteLine(model.Name);
    }
}

打印:

5
bar

并将其转换为典型的ASP.NET MVC模式:

[HttpPost]
public ActionResult Update(MyViewModel viewModel)
{
    if (!ModelState.IsValid)
    {
        // validation failed => redisplay view 
        return View(viewModel);
    }

    // fetch the domain entity that we want to udpate
    DomainModel model = _repository.Get(viewModel.Id);

    // now merge the properties
    Mapper.Map(viewModel, model);

    // update the domain model
    _repository.Update(mdoel);

    return RedirectToAction("Success");
}
相关问题