asp.net-mvc-2 – 使用或不使用AutoMapper的“合并”模型和ViewModel?

我目前正在使用viewmodels将我的Views与实际的Model结构分开.

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

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

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

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

例:

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

解决方法

So i need a way to merge a viewmodel into a persistence entity. Can I
do that with AutoMapper,or do I have to do it manually?

是的,你可以用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");
}

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...