简体   繁体   中英

Automapper map custom collection

Hi im having difficulties mapping a custom pagedlist collection i have created.

I have a pagedList interface like this:

public interface IPagedList<T> : IList<T>

And the implementation:

public class PagedList<T> : List<T>, IPagedList<T>

Mapping config:

Mapper.CreateMap<User, DestinationViewModel>()
  .ForMember(f => f.Score, m => m.MapFrom(s => s.anotherProperty));

I try to map a collection in my controller action like this:

var users = userService.GetPagedUsers(page, size, sort, direction);
var model = Mapper.Map<IPagedList<User>, IPagedList<DestinationViewModel>>(users);

Firstly, is it even possible to do this? I have had a scout around on stack and havent found a definitive answer. I have had no luck so far i have only received InvalidCastOperations cannot map generic collection of User to pagedlist of DestinationViewModel, which were thrown by automapper. Using a different list type like IList when mapping to the model works, but I need to use the IPagedList interface for all the paging stuff it has. Any help would be greatly appreciated, been pulling my hair out too long on this.

Ended up finding an answer after more research, which is no, automapper doesnt support my scenario out out of the box. The two options from here are: To a custom IObjectMapper, using the existing Array/EnumerableMappers as a guide, or write a custom TypeConverter.

In fact, I believe there is a solution to this question.

Mapping config:

Mapper.CreateMap<User, DestinationViewModel>();
Mapper.CreateMap<PagedList<User>, PagedList<DestinationViewModel>>()
      .AfterMap((s, d) => Mapper.Map<List<User>, List<DestinationViewModel>>(s, d));

Then in service/controller:

var users = userService.GetPagedUsers(page, size, sort, direction);
var model = Mapper.Map<PagedList<User>, PagedList<DestinationViewModel>>(users);

I have not tried using the interface (IPagedList), only implementation (PagedList).

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