2

I have a viewmodel containing IList of viewmodels:

 public class MyCustomViewModel
    {
        public IList<ItemViewModel> Items { set; get; }
        public IList<PersonViewModel> Persons { set; get; }

        public MyCustomViewModel()
        {

        }
    }

In my controller's Index action method I'm not able to figure out how to correctly map this kind of nested viewmodels.

Normaly I would do something like:

IList<Item> items= db.Items.ToList();
var viewModel = Mapper.Map<IList<ItemViewModel>>(item);

How would that work with a viewmodel containing several other viewmodels? I've been trying to create new instances of each viewmodel separately but I fail to see how to map them all to my custom viewmodels.

I can't map viewmodels to other viewmodels, can I?

Orphu.of.io
  • 125
  • 1
  • 16
  • If your viewmodels are identical it should work no problem if not you have to manually define mapping . – COLD TOLD Apr 01 '14 at 16:36
  • Try this http://stackoverflow.com/questions/13348812/how-to-use-automapper-to-create-complex-viewmodel-objects-from-a-simple-object-a/13355873#13355873 or http://stackoverflow.com/questions/20270983/ienumerable-to-entitycollection-failed-mapping-with-automapper-using-nested-mapp/20271546#20271546 – Prasad Kanaparthi Apr 01 '14 at 16:38

1 Answers1

2

As long as you have defined a map for both of the view model types, autoMapper will map the nested view models.

For example, if I have a ParentObjectViewModel with a property of type ChildObjectViewmodel, I'd need to make sure I had built a map between them. Automapper will handle the fact that your property is IList.

    Mapper.CreateMap<ParentObjectViewmodel, ParentDataObject>();
    Mapper.CreateMap<ChildObjectViewmodel, ChildDataObject>();

Of course, if your property names don't match for the view model and data object, you'll need to specify that to Automapper.

EDIT: For your example it sounds like you just want to be able to map the child object (property). So you would use:

  Mapper.CreateMap<ItemViewModel, Item>();

This would allow you to automap from any ItemViewModel type to any Item type (including ILists of those objects). In the CreateMap call the source object type is on the left and the destination type is on the right. If you want to map back and forth, just call CreateMap twice.

CuriousLayman
  • 207
  • 1
  • 10
  • This worked when I added a ParentDataObject but would it be possible without it? I was thinking that having ChildDataObjects would be enough since my ParentObjectViewModel is just a collection of different models I need for my custom view and does not have real business logic of its own (it just exists for presentation purpose). Will accept your answer once I clarified this :) – Orphu.of.io Apr 02 '14 at 07:58