具有动作的自动映射器地图集合

automapper map collections with action

我有以下代码

IList<ConfigurationDto> result = new List<ConfigurationDto>();
foreach (var configuration in await configurations.ToListAsync())
{
    var configurationDto = _mapper.Map<ConfigurationDto>(configuration);
    configurationDto.FilePath = _fileStorage.GetShortTemporaryLink(configuration.FilePath);
    result.Add(configurationDto);
}
return result;

如果使用 foreach,我该如何使用 automapper?我可以映射集合,但是如何为每个项目调用 _fileStorage.GetShortTemporaryLink

我看过AfterMap,但我不知道如何从dest得到FilePath,并把它一一映射到src。我可以为此使用自动映射器吗?

public class ConfigurationDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Version { get; set; }
    public DateTime CreateDateTime { get; set; }
    public long Size { get; set; }
    public string FilePath { get; set; }
}

您可以使用 IValueResolver 界面来配置您的地图以从函数映射 属性。类似于下面的示例。

public class CustomResolver : IValueResolver<Configuration, ConfigurationDto, string>
{
    private readonly IFileStorage fileStorage;

    public CustomResolver(IFileStorage fileStorage)
    {
        _fileStorage= fileStorage;
    }

    public int Resolve(Configuration source, ConfigurationDto destination, string member, ResolutionContext context)
    {
        return _fileStorage.GetShortTemporaryLink(source.FilePath);
    }
}

Once we have our IValueResolver implementation, we’ll need to tell AutoMapper to use this custom value resolver when resolving a specific destination member. We have several options in telling AutoMapper a custom value resolver to use, including:

  • MapFrom<TValueResolver>
  • MapFrom(typeof(CustomValueResolver))
  • MapFrom(aValueResolverInstance)

然后您应该配置您的地图以使用自定义解析器将 FilePath 属性 映射到 ConfigurationDto

var configuration = new MapperConfiguration(cfg => cfg.CreateMap<Configuration, ConfigurationDto>()
                   .ForMember(dest => dest.FilePath, opt => opt.MapFrom<CustomResolver>()));

您可以在此 link 查看更多关于自定义值解析器的信息:http://docs.automapper.org/en/stable/Custom-value-resolvers.html