简体   繁体   English

Automapper映射自定义集合

[英]Automapper map custom collection

Hi im having difficulties mapping a custom pagedlist collection i have created. 嗨,我在映射我创建的自定义pagedlist集合时遇到困难。

I have a pagedList interface like this: 我有这样的pagedList接口:

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. 到目前为止,我还没有运气,我只收到了InvalidCastOperations无法将User的通用集合映射到Automapper抛出的DestinationViewModel的pagedlist中。 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. 映射到模型时,可以使用类似IList的其他列表类型,但是我需要为其所有分页内容使用IPagedList接口。 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. 经过更多研究后最终找到答案,这是不对的,automapper不支持我的方案。 The two options from here are: To a custom IObjectMapper, using the existing Array/EnumerableMappers as a guide, or write a custom TypeConverter. 这里有两个选项:对于自定义IObjectMapper,使用现有的Array / EnumerableMappers作为指南,或编写自定义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). 我没有尝试使用接口(IPagedList),仅尝试实现(PagedList)。

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

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