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; }
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.