使用Automapper将多个模型映射到ViewModel

使用Automapper将多个模型映射到ViewModel

问题描述:

比方说,我有两个模型,我的视图需要这些模型提供信息.我正在使用自动映射器将每个模型的各个部分映射到单个ViewModel中.这是好习惯吗?如果没有,我还可以通过哪些其他方式解决此问题?

Let's say I have two models that my View requires information from. I am using automapper to map parts of each model into a single ViewModel. Is this good practice? If not, what other ways can I approach this problem?

如果可以的话,您应该再添加一些代码.但是,为什么需要为此使用automapper?我认为应该直截了当.

You should put a little more code if you can. But why do you need to use automapper for this? Should be straight forward I think.

public class ModelA
{
    [stuff via automapper?]
}
public class ModelB
{
    [stuff via automapper?]
}
public class HappyViewModel
{
    public ModelA ModelA { get; set; }
    public ModelB ModelB { get; set; }
}

控制器

public ActionResult Index()
{
    var model = new HappyViewModel();
    model.ModelA = [populate me]
    model.ModelB = [populate me]
    return View(model)
}

查看

@model HappyViewModel
Model.ModelA.[stuff]
Model.ModelB.[stuff]