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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....