How to map lists with ValueInjector

Brendan Vogt picture Brendan Vogt · Oct 24, 2011 · Viewed 10.1k times · Source

I am using ASP.NET MVC 3.

Can someone please help me clarify what's happening here:

var person = new PersonRepository().Get();

var personViewModel = new PersonViewModel();
personViewModel.InjectFrom<LoopValueInjection>(person)
     .InjectFrom<CountryToLookup>(person);

I have a grid on my Index view. Each row is an instance of a CategoryViewModel. So what I do is to get a list of all the categories and then map each Category to a CategoryViewModel, and then pass this list of CategoryViewModels to the view. Hou would I do a mapping like that?

IEnumerable<Category> categoryList = categoryService.GetAll();

I thought the following would work but it doesn't:

// Mapping
IList<CategoryViewModel> viewModelList = new List<CategoryViewModel>();
viewModelList.InjectFrom(categoryList);

Answer

Darin Dimitrov picture Darin Dimitrov · Oct 24, 2011

AFAIK value injecter doesn't support automatic collection mapping like AutoMapper but you could use a simple LINQ expression and operate on each element:

IEnumerable<Category> categoryList = categoryService.GetAll();
IList<CategoryViewModel> viewModelList = categoryList
    .Select(x => new CategoryViewModel().InjectFrom(x)).Cast<CategoryViewModel>()
    .ToList();