C# 使用AutoMapper映射ViewModel/partials

C# 使用AutoMapper映射ViewModel/partials,c#,asp.net-mvc,automapper,C#,Asp.net Mvc,Automapper,我已经创建了表示模型,我想用AutoMapper将其映射到ViewModel中。 ViewModel是复合的/因为我使用的是partials,我想在其他视图/partials上重用KeyboardsViewModel 如何将此演示模型映射到ViewModel的设置映射?这是正确的方法吗 谢谢 public class MainPresentationModel : BasePresentationModel { // Should map into the MainViewModel.Key

我已经创建了表示模型,我想用AutoMapper将其映射到ViewModel中。 ViewModel是复合的/因为我使用的是partials,我想在其他视图/partials上重用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使用接口。例如,partial可以接受IKeyboardsViewModel,这样就不必担心复杂的继承层次结构。然后,您可以只给每个部分一个主模型的切片。

这种方法肯定有效。您还可以为这些复合UI使用接口。例如,partial可以接受IKeyboardsViewModel,这样就不必担心复杂的继承层次结构。然后,您可以只为每个部分提供主模型的一个切片