简体   繁体   中英

Automapper not mapping IEnumerable<T> to IEnumerable<T> in Viewmodel

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM