简体   繁体   中英

How can I use AutoMapper to map one collection to another?

I would like to use AutoMapper to map one collection to another. I know that the convention is to set up a mapping for the child object:

Mapper.CreateMap<User, UserDto>();

And then this works fine:

Mapper.Map<List<UserDto>>(UserRepo.GetAll());

But I'd still like to map the list anyway. For example, I'd like to do something like this:

Mapper.CreateMap<List<User>, List<UserDto>>()
    .AfterMap((source, destination) =>
        {
            // some complex/expensive process here on the entire user list
            // such as retrieving data from an external database, etc
        }

That way I can still use the first map but also to do something custom with the user list as well. In my scenario, it's looking up event IDs in an external database in another datacenter and I'd like to optimise it by only looking up unique IDs, not doing it object-by-object.

However, when I attempt to map a list of User to a list of UserDto, the mapping just returns an empty list. Putting a breakpoint in the AfterMap function reveals that the destination variable holds an empty list. How can I make AutoMapper do this correctly?

Well, that was embarrassing. Five minutes later, I just figured out that you can add a ConvertUsing function which just proxies to a member-by-member mapping:

Mapper.CreateMap<List<User>, List<UserDto>>()
    .ConvertUsing(source => 
        {
            // some complex/expensive process here on the entire user list
            // such as retrieving data from an external database, etc
            return source.Select(Mapper.Map<User, UserDto>).ToList());
        });

Perhaps that's not how you're meant to do it but it works for me.

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