开发者

Map ViewModel / partials with AutoMapper

I have created presentation model and I want to map it (with AutoMapper) into the ViewModel. ViewModel is composite / because I'm using partials and I want to reuse for example KeyboardsViewModel also on other views/partials.

How can I map (setup mapping) this presentation model into the ViewModel? Is this the right approach?

Thanks!

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

Edited: After trying out I think that this is one option:

        Mapper.CreateMap<Ma开发者_StackOverflow社区inPresentationModel, MainViewModel>()
            .ForMember(d => d.Keyboards, opt => opt.MapFrom(src => src));
        Mapper.CreateMap<MainPresentationModel, KeyboardsViewModel>();

It seems that it works, but I am not sure if this is optimal/correct way...


This way definitely works. You can also use interfaces for these composite UIs. For example, the partial could accept an IKeyboardsViewModel, and then you won't have to worry about complex inheritance hierarchies. You can then just give each partial a slice of the main model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜