views:

140

answers:

1

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<MainPresentationModel, 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...

A: 

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.

Jimmy Bogard