关于 c#:automapper map collections with action

automapper map collections with action

我有以下代码

1
2
3
4
5
6
7
8
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 。我可以为此使用自动映射器吗?

1
2
3
4
5
6
7
8
9
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 接口来配置您的地图以从函数映射属性。类似于下面的示例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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, wea€?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
  • MapFrom(typeof(CustomValueResolver))
  • MapFrom(aValueResolverInstance)

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

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

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