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?我可以映射集合,但是如何为每个项目调用
我看过 AfterMap 但我不知道如何从
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; } } |
您可以使用
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)
然后您应该配置您的地图以使用自定义解析器来映射
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