automapper map collections with action

*爱你&永不变心* 提交于 2020-01-04 04:34:11

问题


I have the following code

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;

How can I use automapper instead if foreach? I can map collection, but how to call _fileStorage.GetShortTemporaryLink for each item?

I have looked at AfterMap but I don't know how to get FilePath from dest and map it to src one by one. Can I use automapper for that?

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

回答1:


You can use the IValueResolver interface to configure your map to map a property from a function. Something like the sample bellow.

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)

Then you should configure your map to use the custom resolver for mapping the FilePath property on ConfigurationDto.

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

You can see more about custom value resolvers at this link: http://docs.automapper.org/en/stable/Custom-value-resolvers.html



来源:https://stackoverflow.com/questions/59049913/automapper-map-collections-with-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!