使用Automapper将多个模型映射到ViewModel [英] Mapping multiple Models to ViewModel with Automapper

查看:171
本文介绍了使用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]

这篇关于使用Automapper将多个模型映射到ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆