[英]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
?
我看過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; }
}
您可以使用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<TValueResolver>
MapFrom(typeof(CustomValueResolver))
MapFrom(aValueResolverInstance)
然后您應該配置您的映射以使用自定義解析器來映射ConfigurationDto
上的FilePath
屬性。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.