Automapper 5.2映射时没有记录



我正在使用从DTO到模型到DTO的AutoMapper 5.2映射。但是我遇到的问题是我进行映射时有0个元素。这两个实体是相同的。

automapperconfiguration.cs

public class AutoMapperConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(x =>
        {
            x.CreateMap<PaisDto, Pais>().ReverseMap();
            x.CreateMap<List<PaisDto>, List<Pais>>().ReverseMap();
            x.CreateMap<Pais, PaisDto>().ReverseMap();
            x.CreateMap<List<Pais>, List<PaisDto>>().ReverseMap();
        });
    }
}

paisservice.cs

public IEnumerable<PaisDto> GetAll()
{
    AutoMapperConfiguration.Configure();
    List<PaisDto> dto = new List<PaisDto>();
    IEnumerable<Pais> paises = _paisRepository.GetPaisAll();
    dto = Mapper.Map<List<Pais>,List<PaisDto>>(paises.ToList());
    return dto.ToList();
}

会发生什么?

不确定这是否是您要寻找的东西,但可以为单个PAIS/PAISDTO

创建地图

,当您想映射列表时,您可以使用自动应用程序的EF6扩展

https://www.nuget.org/packages/automapper.ef6/

然后您只能使用

.ProjectTo<TDestination>(mapperConfig) 

需要映射的列表

您不需要从列表中映射到列表 - 自动应用程序知道列表,您只需要告诉它有关单个项目的信息:

Mapper.Initialize(x =>
{
    x.CreateMap<Pais, PaisDto>().ReverseMap();
});

然后它可以单独映射列表:

IEnumerable<Pais> paises = _paisRepository.GetPaisAll();
List<PaisDto> dto = Mapper.Map<List<PaisDto>>(paises);
return dto;

您也不需要在列表上致电.tolist,这只是制作另一个副本。

最新更新