简体   繁体   English

如何使用AutoMapper将一个集合映射到另一个集合?

[英]How can I use AutoMapper to map one collection to another?

I would like to use AutoMapper to map one collection to another. 我想使用AutoMapper将一个集合映射到另一个集合。 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. 在我的场景中,它在另一个数据中心的外部数据库中查找事件ID,我想通过仅查找唯一ID来优化它,而不是逐个对象地进行优化。

However, when I attempt to map a list of User to a list of UserDto, the mapping just returns an empty list. 但是,当我尝试将User列表映射到UserDto列表时,映射只返回一个空列表。 Putting a breakpoint in the AfterMap function reveals that the destination variable holds an empty list. AfterMap函数中放置断点会显示destination变量包含空列表。 How can I make AutoMapper do this correctly? 如何让AutoMapper正确执行此操作?

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: 五分钟后,我发现你可以添加一个ConvertUsing函数,它只代表一个成员映射:

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. 也许这不是你的意思,但它对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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