Automapper:将对象映射到 LIST

Automapper: Mapping an object to a LIST

我有一个类型SupportedCurrencies,其中包含类型为Currency的对象列表:

  public class SupportedCurrencies
        {
            public List<Currency> Currencies { get; set; }
        }
  public class Currency
    {
        public string Code { get; set; }    
        public string AmountMin { get; set; }
        public string AmountMax { get; set; }
    }

我想将它映射到 SupportedCurrency 类型的对象列表:

    public class SupportedCurrency
    {
        public string CurrencyCode { get; set; }
        public string MinAmount { get; set; }
        public string MaxAmount { get; set; }
    }

在我的映射配置文件中,我有以下映射:

CreateMap<Response.Currency, SupportedCurrency>()
            .ForMember(p => p.MinAmount, q => q.MapFrom(r => r.AmountMin))
            .ForMember(p => p.MaxAmount, q => q.MapFrom(r => r.AmountMax))
            .ForMember(p => p.CurrencyCode, q => q.MapFrom(r => r.Code));

CreateMap<SupportedCurrencies, IList<SupportedCurrency>>().ConvertUsing(MappingFunction);

转换器看起来像这样:

 private IList<SupportedCurrency> MappingFunction(SupportedCurrencies arg1, IList<SupportedCurrency> arg2, ResolutionContext arg3)
        {
            foreach (var item in arg1.Currencies)
            {
                arg2.Add(arg3.Mapper.Map<SupportedCurrency>(item)); 
            }
            return arg2;
        }

但是当我尝试映射它时:

_mapper.Map<IList<SupportedCurrency>>(obj01.SupportedCurrencies);

我收到一条异常消息:

Method 'get_Item' in type 'Proxy_System.Collections.Generic.IList`1 is not implemented.

我做错了什么?

删除了 CreateMap 的静态版本:

不知道你有没有升级的选择。但是对于最新的 AutoMapper (10.1.1),下面的代码有效(你没有给出完整的代码所以我创建了 SupportedCurrencies 的对象)

            var config = new MapperConfiguration(cfg => {
                cfg.CreateMap<Currency, SupportedCurrency>()
                    .ForMember(p => p.MinAmount, q => q.MapFrom(r => r.AmountMin))
                    .ForMember(p => p.MaxAmount, q => q.MapFrom(r => r.AmountMax))
                    .ForMember(p => p.CurrencyCode, q => q.MapFrom(r => r.Code));

            });


            SupportedCurrencies supportedCurrencies = new SupportedCurrencies();
            IMapper mapper = config.CreateMapper();
            mapper.Map<IList<SupportedCurrency>>(supportedCurrencies);