【问题标题】:automapper map collections with action带有动作的自动映射器地图集合
【发布时间】:2019-12-04 20:57:59
【问题描述】:

我有以下代码

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; }
}

【问题讨论】:

    标签: c# .net asp.net-core automapper


    【解决方案1】:

    您可以使用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);
        }
    }
    

    一旦我们有了 IValueResolver 实现,我们就需要告诉 AutoMapper 在解析特定目标成员时使用这个自定义值解析器。在告诉 AutoMapper 使用自定义值解析器时,我们有多种选择,包括:

    • MapFrom&lt;TValueResolver&gt;
    • MapFrom(typeof(CustomValueResolver))
    • MapFrom(aValueResolverInstance)

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多