Reputation: 12904
I have the following classes defined;
Data.Models.Lists.List
Infrastructure.Models.Lists.List
Both contain the following fields;
public int Id { get; set; }
public string Description { get; set; }
I also have this View Model defined;
public class IndexViewModel
{
public IEnumerable<Infrastructure.Models.Lists.List> Lists { get; set; }
}
Within my Automapper configuration, I am simply doing the following;
cfg.CreateMap< Data.Models.Lists.List, Infrastructure.Models.Lists.List>()
Which I thought would be enough, but I also added this;
cfg.CreateMap<IEnumerable<List>,Models.Lists.IndexViewModel>();
However, when I attempt to map the items in my controller;
var items = ListsService.GetLists(CurrentPrincipal.Id);
var model = Mapper.Map<IndexViewModel>(items);
model.Lists is always null, although items has 22. What else needs to be added in order to get this mapping working?
Upvotes: 2
Views: 4182
Reputation: 205829
AutoMapper does automatic mapping of the properties of the two types with the same name.
In order to map the whole source object to a target object property as in your case, you have to specify that explicitly:
cfg.CreateMap<IEnumerable<Data.Models.Lists.List>, Models.Lists.IndexViewModel>()
.ForMember(dest => dest.Lists, m => m.MapFrom(src => src));
Upvotes: 5
Reputation: 6832
You are mapping your items to the instance of the viewmodel directly, not it's Lists
property. Your first mapping config is fine, the second one you don't need.
var model = new IndexViewModel()
{
Lists = Mapper.Map<IEnumerable<Infrastructure.Models.Lists.List>>(items)
};
Upvotes: 1