繁体   English   中英

Automapper映射自定义集合

[英]Automapper map custom collection

嗨,我在映射我创建的自定义pagedlist集合时遇到困难。

我有这样的pagedList接口:

public interface IPagedList<T> : IList<T>

并执行:

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

映射配置:

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

我尝试像这样在控制器操作中映射集合:

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

首先,是否有可能做到这一点? 我在堆上有一个侦察员,还没有找到明确的答案。 到目前为止,我还没有运气,我只收到了InvalidCastOperations无法将User的通用集合映射到Automapper抛出的DestinationViewModel的pagedlist中。 映射到模型时,可以使用类似IList的其他列表类型,但是我需要为其所有分页内容使用IPagedList接口。 任何帮助,将不胜感激,因为将我的头发拉得太久了。

经过更多研究后最终找到答案,这是不对的,automapper不支持我的方案。 这里有两个选项:对于自定义IObjectMapper,使用现有的Array / EnumerableMappers作为指南,或编写自定义TypeConverter。

实际上,我相信这个问题可以解决。

映射配置:

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

然后在服务/控制器中:

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

我没有尝试使用接口(IPagedList),仅尝试实现(PagedList)。

暂无
暂无

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

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