Карта AutoMapper из коллекции IConfigurationSection - PullRequest
1 голос
/ 06 июня 2019

Я просмотрел документацию по отображению коллекций и вложенному отображению и отображению вложенной коллекции, но все еще не могу справиться с моим делом.
У меня есть следующий файл конфигурации json:

{
  "startupConfig": {
    "noSubscription": {
      "calls": [
        {
          "percentage": 30,
          "techPriority": 1,
          "timePriority": 2
        },
        {
          "percentage": 30,
          "techPriority": 1,
          "timePriority": 2
        }
      ]
    }
  }
}

А вот мое чтение кода из файла:

var config = _mapper.Map<FeedConfiguration>(_configuration
    .GetSection("startupConfig").GetChildren()
    .FirstOrDefault(cc => cc.Key == "noSubscription")?.GetChildren());

Однако отображение не работает. Вот код конфигурации отображения:

CreateMap<IEnumerable<IConfigurationSection>, CallConfiguration>()
    .ForMember(cc => cc.Percentage,
        mo => mo.MapFrom(css => css.FirstOrDefault(cs => cs.Key == "percentage").Value))
    .ForMember(cc => cc.TechPriority,
        mo => mo.MapFrom(css => css.FirstOrDefault(cs => cs.Key == "techPriority").Value))
    .ForMember(cc => cc.TimePriority,
        mo => mo.MapFrom(css => css.FirstOrDefault(cs => cs.Key == "timePriority").Value));
CreateMap<IEnumerable<IConfigurationSection>, FeedConfiguration>()
    .ForMember(fc => fc.CallsConfig,
        mo => mo.MapFrom(css => css.FirstOrDefault(cs => cs.Key == "calls").GetChildren()));

Классы, на которые я отображаю:

namespace FeedService.FeedConfigurations
{
    public class FeedConfiguration
    {
        public ICollection<CallConfiguration> CallsConfig { get; set; }
    }

    public class CallConfiguration
    {
        public int Percentage { get; set; }
        public int TechPriority { get; set; }
        public int TimePriority { get; set; }
    }
}

И вот исключение, которое я получаю:

AutoMapper.AutoMapperConfigurationException: 
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
=============================================================================================================
AutoMapper created this type map for you, but your types cannot be mapped using the current configuration.
IConfigurationSection -> CallConfiguration (Destination member list)
Microsoft.Extensions.Configuration.IConfigurationSection -> FeedService.FeedConfigurations.CallConfiguration (Destination member list)

Unmapped properties:
Percentage
TechPriority
TimePriority

Буду очень благодарен за вашу помощь!
=== Примечание ===
Мне все еще нужен ответ на вопрос, но я разместил новый с более подробным объяснением здесь .

1 Ответ

1 голос
/ 06 июня 2019

Вам на самом деле не нужен Automepper здесь. Просто используйте привязку ядра .net по умолчанию.

переименуйте это

 public ICollection<CallConfiguration> CallsConfig { get; set; }

до Calls

тогда используйте что-то вроде

 var config  = _configuration.GetSection("startupConfig:noSubscription").Get<FeedConfiguration>();
...