c# - 使用 AutoMapper 映射 ViewModel/partials

标签 c# asp.net-mvc automapper

我已经创建了表示模型​​,我想将它(使用 AutoMapper)映射到 ViewModel。 ViewModel 是复合的/因为我正在使用局部 View 并且我想在其他 View /局部 View 上重用例如 KeyboardsViewModel。

如何将此表示模型映射(设置映射)到 ViewModel 中?这是正确的方法吗?

谢谢!

public class MainPresentationModel : BasePresentationModel
{
  // Should map into the MainViewModel.Keyboards.Keyboards
  public int DefaultKeyboard { get; set; }
  // Should map into the MainViewModel.Keyboards.DefaultKeyboard
  public IList<Keyboard> Keyboards { get; set; }
  // Should map into the MainViewModel.Something
  public string Something { get; set; }
}

public class MainViewModel : BaseViewModel
{
  public KeyboardsViewModel Keyboards { get; set; }
  public string Something { get; set; }
}

public class KeyboardsViewModel
{
  public int DefaultKeyboard { get; set; }
  public IList<Keyboard> Keyboards { get; set; }
}

编辑: 尝试后,我认为这是一种选择:

        Mapper.CreateMap<MainPresentationModel, MainViewModel>()
            .ForMember(d => d.Keyboards, opt => opt.MapFrom(src => src));
        Mapper.CreateMap<MainPresentationModel, KeyboardsViewModel>();

似乎可行,但我不确定这是否是最佳/正确的方式...

最佳答案

这种方式绝对有效。您还可以使用这些复合 UI 的界面。例如,部分可以接受 IKeyboardsViewModel,这样您就不必担心复杂的继承层次结构。然后,您可以只给每个部分一个主模型的切片。

关于c# - 使用 AutoMapper 映射 ViewModel/partials,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2130668/

相关文章:

c# - 实现复选框产品过滤器 ASP.NET MVC - 如何通过 URL 传递集合中的数据?

C#MVC : User Password Reset Controller: Issues with email addresses as usernames

c# - 使用 Automapper 映射后嵌套对象成员为 null

model - 自动映射器在 MVVM 应用程序中的使用

c# - MS Word 格式数据系列线帽类型

c# - Selenium - C# - Webdriver - 无法找到元素

c# - Selenium 不根据名称输入字符串?

c# - 在 C# 应用程序中显示 html/css 网页?

c# - 使用 Cookie 进行 MVC 单元测试

c# - 如何在 ASP.NET Core 中手动注册 AutoMapper 配置文件?