简体   繁体   English

带有动作的自动映射器地图集合

[英]automapper map collections with action

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?如果foreach,我该如何使用automapper? I can map collection, but how to call _fileStorage.GetShortTemporaryLink for each item?我可以映射集合,但是如何为每个项目调用_fileStorage.GetShortTemporaryLink

I have looked at AfterMap but I don't know how to get FilePath from dest and map it to src one by one.我看过AfterMap但我不知道如何从dest获取FilePath并将其一一映射到src 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.您可以使用IValueResolver接口将地图配置为从函数映射属性。 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.一旦我们有了IValueResolver实现,我们就需要告诉 AutoMapper 在解析特定目标成员时使用这个自定义值解析器。 We have several options in telling AutoMapper a custom value resolver to use, including:我们有几个选项可以告诉 AutoMapper 要使用的自定义值解析器,包括:

  • 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 .然后您应该配置您的映射以使用自定义解析器来映射ConfigurationDto上的FilePath属性。

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您可以在此链接中查看有关自定义值解析器的更多信息: http : //docs.automapper.org/en/stable/Custom-value-resolvers.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM