具有动作的自动映射器地图集合 [英] automapper map collections with action
问题描述
我有以下代码
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
?
How can I use automapper instead if foreach? I can map collection, but how to call _fileStorage.GetShortTemporaryLink
for each item?
我查看了 AfterMap 但我不知道如何从dest
中获取FilePath
并将其逐一映射到src
.我可以使用自动映射器吗?
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; }
}
推荐答案
您可以使用IValueResolver
界面来配置地图,以映射功能中的属性.像波纹管样的东西.
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);
}
}
一旦实现了
IValueResolver
,我们将需要告诉AutoMapper在解析特定目标成员时使用此自定义值解析器.在告诉AutoMapper一个要使用的自定义值解析器时,我们有几种选择,包括:
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)
MapFrom<TValueResolver>
MapFrom(typeof(CustomValueResolver))
MapFrom(aValueResolverInstance)
然后,您应该将地图配置为使用自定义解析程序在ConfigurationDto
上映射FilePath
属性.
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>()));
您可以在以下链接中了解有关自定义值解析器的更多信息: http ://docs.automapper.org/en/stable/Custom-value-resolvers.html
You can see more about custom value resolvers at this link: http://docs.automapper.org/en/stable/Custom-value-resolvers.html
这篇关于具有动作的自动映射器地图集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!